[英]unable to access next node for Linked List while reversing a Linked List in python
我對python有點陌生,我已經看到了解決反向鏈接列表問題的正確解決方案,但是我想知道為什么我的解決方案不起作用。 特別地,由於“ new_list.head.next = prev”這一行,反向函數停留在以下代碼的while循環內
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
def reverse(linked_list):
new_list = LinkedList()
if linked_list is None:
return new_list
node = linked_list.head
new_list.head = node
while node.next:
prev = node
node = node.next
new_list.head = node
new_list.head.next = prev
return new_list
if __name__ == "__main__":
a = LinkedList()
b = [1,2,3,4,5]
for item in b:
a.append(item)
print a
c = reverse(a)
print c
如果您使用Python3
標記問題,請確保它在python 3中運行。
原因是因為您混淆了點並創建了無限循環。 打印該value
,它可以幫助您發現錯誤。 我將使用這些值指出問題。
while node.next:
# First node that comes in value = 1
print(node.value) #
prev = node # prev = 1
node = node.next # node = 2
new_list.head = node # You are setting the head = 2 (i.e. head = node.next)
new_list.head.next = prev # You are setting next of head = 1 (i.e. head.next = node.next.next)
# however this also set node.next.next = 1
# So going into the next loop: node.value = 2 and node.next.value = 1
由於指針混亂,您將永遠在第一個節點和第二個節點之間循環。
這是您的reverse
情況:
def reverse(linked_list):
new_list = LinkedList()
if linked_list is None:
return new_list
node = linked_list.head
new_list.head = Node(node.value)
while node.next:
node = node.next
prev_head = new_list.head
new_list.head = Node(node.value)
new_list.head.next = prev_head
return new_list
有了它,我得到了所需的print c
輸出print c
: [5, 4, 3, 2, 1]
一般建議:創建新節點,而不是分配給初始列表中的節點。
如果您想到兩個引用,那么對此(至少對我來說)要容易一點:
•您未曾看到的原始清單的其余部分之一
•新清單的首位
在每次迭代時,將剩余部分向上移動,並將舊的剩余部分設置為新列表的開頭。 順序在這里很重要-如您所見,如果不小心,很容易意外地在指向同一節點的兩個不同變量上進行下一步更改:
def reverse(linked_list):
new_list = LinkedList()
if linked_list is None:
return new_list
remaining = linked_list.head
while remaining:
prev_head = new_list.head # the old head becomes the first link
new_list.head = remaining # new head becomese the first remaining
remaining = remaining.next # move remaing one up the chain
new_list.head.next = prev_head # point the new head to the previous
return new_list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.