1
我一直在學習鏈表,並且在python中實現一個比我想象的要容易。但是,當它解決了「在鏈表中交換對」的問題時,出於某種原因,我的第二個鏈接在交換過程中消失了。我一直在盯着這個世界,嘗試不同的解決方案,我在網上找到。他們都得到相同的結果,這表明我的問題是與列表本身的實施。或者我在某個地方發現了一個我看不見的愚蠢錯誤!我會感激一雙新鮮的眼睛。我做錯了什麼?在Python中鏈接列表中交換對,一個鏈接消失?
class Node:
def __init__(self, val):
self.value = val
self.next = None
class LinkedList:
def __init__(self, data):
self.head = Node(data)
def printList(self, head):
while head:
print("->" , head.value)
head = head.next;
def swapPairsR(self, node): # recursive
if node is None or node.next is None:
return node
ptrOne = node
ptrTwo = node.next
nextPtrTwo = ptrTwo.next
# swap the pointers here at at the rec call
ptrTwo.next = node
newNode = ptrTwo
ptrOne.next = self.swapPairsR(nextPtrTwo)
return newNode
def swapPairsI(self, head): # iterative
prev = Node(0)
prev.next = head
temp = prev
while temp.next and temp.next.next:
ptrOne = temp.next
ptrTwo = temp.next.next
# change the pointers to the swapped pointers
temp.next = ptrTwo
ptrOne.next = ptrTwo.next
ptrTwo.next = ptrOne
temp = temp.next.next
return prev.next
thisLList = LinkedList(1)
thisLList.head.next = Node(2)
thisLList.head.next.next = Node(3)
thisLList.head.next.next.next = Node(4)
thisLList.head.next.next.next.next = Node(5)
thisLList.printList(thisLList.head)
print("--------------")
thisLList.swapPairsI(thisLList.head)
thisLList.printList(thisLList.head)
編輯:我的輸出:
-> 1
-> 2
-> 3
-> 4
-> 5
--------------
-> 1
-> 4
-> 3
-> 5
哦,我的天啊,我什至沒有想到這一點。呻吟!謝謝,當然這也是我的遞歸函數「錯誤」。 – dgBP