反向链接列表并将其显示为原始列表

时间:2018-08-22 00:16:45

标签: python data-structures linked-list

我成功地实现了带有显示列表元素的显示功能的单个链接列表。我创建了一个迭代反向函数,但是显示的列表缺少最后一个元素,而是显示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]

1 个答案:

答案 0 :(得分: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时,会将head设置为非空白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]