问题
I have been learning about linked lists, and implementing one in python has been easier than I expected. However, when it has come to solving the problem of "swapping pairs in a linked list", for some reason my second link disappears during the swap. I've been staring at this for ages and trying different solutions I found online. They all get the same result which suggests my problem is with the implementation of the list itself. Or I've made a silly error somewhere that I can't see! I would be grateful for a fresh pair of eyes. What have I done wrong?
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)
Edit: my output:
-> 1
-> 2
-> 3
-> 4
-> 5
--------------
-> 1
-> 4
-> 3
-> 5
回答1:
Your swapPairsI
function is returning the new head
of your linked list.
You need to update it accordingly:
thisLList.head = thisLList.swapPairsI(thisLList.head)
Or better yet, you should change your swapPairsI
function so that it doesn't have to take a node as parameter:
def swapPairsI(self): # iterative
prev = Node(0)
prev.next = self.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
self.head = prev.next
In which case, you can simply call:
thisLList.swapPairsI()
来源:https://stackoverflow.com/questions/46648779/swapping-pairs-in-a-linked-list-in-python-one-link-disappears