【问题标题】:create a Doubly LinkedList form a list in python从python中的列表创建一个双向链接列表
【发布时间】:2021-07-30 15:32:03
【问题描述】:

我想从 python 中的列表创建一个双向链接列表。代码不工作,你能解释一下我做错了什么吗?

这是我的代码

class Node:
def __init__(self, data):
    self.data = data
    self.next = None
    self.prev = None


class DoublyList:
    def __init__(self, a):
        self.head = None
        self.tail = None
        self.head.next = self.head.prev = self.head
        self.size = 0

    for i in a:
        n = Node(i)
        if (self.head is None):
            self.head = n
            tail = n
        else:
            tail.next = n
            tail = n

def showList(self):
        current = self.head
        
        while current is not None:
            print(current.data)
            current = current.next

测试

lst = [10, 20, 30]
d = DoublyList(lst)
d.showList()

【问题讨论】:

  • 为了帮助人们在答案中归零,如果您解释它“不工作”的原因,甚至提供错误消息(如果有的话),这将非常有帮助。

标签: python-3.x data-structures doubly-linked-list


【解决方案1】:

这段代码应该可以工作,你没有给 self 作为 tail 并且你需要检查 current next 是否为 None

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None


class DoublyList(Node):
    def __init__(self, a):
        self.head = Node
        self.tail = Node
        self.head.next = self.head.prev = self.head
        self.size = 0

        for i in a:
            n = Node(i)
            if (self.head is None):
                self.head = n
                self.tail = n
            else:
                self.tail.next = n
                self.tail = n

    def showList(self):
        current = self.head
        
        while current.next is not None: 
            current = current.next
            print(current.data)
            
lst = [10, 20, 30]
d = DoublyList(lst)
d.showList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多