[英]Reversing Linked List and displaying it like original
我成功地實現了一個帶有打印列表元素的 Display 函數的單鏈表。 我創建了一個迭代反向函數,但顯示的列表缺少最后一個元素並顯示 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]
問題在於,由於節點和鏈表的構造函數,您的鏈表以空白開頭。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.