【问题标题】:Reversing Linked List and displaying it like original反转链接列表并像原来一样显示它
【发布时间】:2018-08-22 00:16:45
【问题描述】:

我成功地实现了一个带有显示功能的单链表,它可以打印列表元素。我创建了一个迭代反向函数,但显示的列表缺少最后一个元素,而是显示 None。

我多次检查我的算法。我有什么遗漏吗?

提前致谢。

class node(object):
    def __init__(self, data=None):
        self.data = data
        self.next = None

class LinkedList(object):
    def __init__(self, head=None):
        self.head = node()

    # append to list
    def append(self, data):
        new_node = node(data)
        current = self.head  # head of the list
        while current.next != None:  # while not last node
            current = current.next  # traverse
        current.next = new_node  # append

    def display(self):
        list = []
        current = self.head
        while current.next != None:
            current = current.next
            list.append(current.data)
        print(list)
        return

    def reverse(self): 
        current = self.head
        prev = None
        while current:
            next_ = current.next
            current.next = prev
            prev = current
            current = next_
        self.head = prev

测试用例:

list = LinkedList()
list.append(0)
list.append(1)
list.append(2)
list.append(3)
list.append(4)
list.display()
list.reverse()
list.display()

输出:

[0, 1, 2, 3, 4]
[3, 2, 1, 0, None]

【问题讨论】:

  • 包含你的 LinkedList() 类是@eyllanesc 要求你做的,尽可能多地运行并向我们展示问题所在。
  • @vividpk21 非常感谢您的澄清。我已经添加了类,代码现在可以运行了。

标签: python data-structures linked-list


【解决方案1】:

问题在于,由于节点和链表的构造函数,您的链表以空白开头。

class node(object):
    def __init__(self, data=None):
        self.data = data
        self.next = None
class LinkedList(object):
    def __init__(self, head=None):
        self.head = node()

如果您在创建新的 LinkedList 对象时注意到,您将得到一个没有数据的头部,并且您在打印语句/附加中通过获取 self.head.next 先进行补偿:

current = self.head  # head of the list
    while current.next != None:  # while not last node

这意味着当您在最后的反向类中设置 self.head 时,您将头部设置为非空白头部,并在打印中跳过它。

为了弥补这一点,您需要创建一个新的空白头并设置在 prev 旁边:

    def reverse(self):
    current = self.head.next
    prev = None
    while current:
        next_ = current.next
        current.next = prev

        prev = current
        current = next_

    #We create a new blank head and set the next to our valid list
    newHead = node()
    newHead.next = prev
    self.head = newHead

输出是

[0, 1, 2, 3, 4]
[4, 3, 2, 1, 0]

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多