[英]Rearrange linked list in python
我正在嘗試使用 Python 解決有關 Cracking the Code Interview 的問題。
問題:例如,假設您有一個鏈表 a1->a2->•••->an->b1->b2 ->••• ->bn 並且您想將其重新排列為 a1->b1 -> a2->b2-> •••->an->bn。 你不知道鏈表的長度(但你知道長度是偶數)。
但事實證明,我的代碼在重新排列后陷入了無限循環。
class Node(object):
def __init__(self, elem, next=None):
self.elem = elem
self.next = next
class SingleLinkList(object):
def __init__(self):
self.head = None
self.next = None
def is_empty(self):
return self.head == None
def append(self,item):
node = Node(item)
if self.is_empty():
self.head = node
node.next=None
else:
cur = self.head
while cur.next != None:
cur=cur.next
cur.next = node
node.next = None
def linked_list_rearrange(self):
fast = self.head
slow = self.head
while fast != None:
fast = fast.next.next
slow = slow.next
fast = self.head
while slow != None:
temp = slow.next
#print(temp.elem)
slow.next = fast.next
fast.next = slow
fast = slow.next
slow = temp
tlist=[0,1,2,3,4,5,6,7,8,9]
ll=SingleLinkList()
for i in tlist:
ll.append(i)
ll.linked_list_rearrange()
cur = ll.head
while cur!= None:
print(cur.elem,end=" ")
cur = cur.next
但是當我通過取前 10 個節點來強制停止循環時,數據看起來是正確的。
while cur!= None:
print(cur.elem,end=" ")
if cur.elem == 9:
break
else:
cur = cur.next
結果:結果N
我不知道為什么我的代碼是錯誤的。 你能幫我解決這個問題嗎?
在第二個while循環中,當slow
在最后一個節點上時,它連接到fast
並接收仍然連接到列表中間節點的那個fast
節點的下一個指針。 這會將下一個鏈接置於slow
,從而在列表中創建循環引用。
為避免這種情況,您可以更改第二個 while 的條件(以檢查何時快速達到初始慢速)或在第二個 while 循環之前斷開初始slow
節點之前的節點的下一個鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.