Swapping Pairs In A Linked List In Python, One Link Disappears?
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 li
Solution 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:
defswapPairsI(self): # iterative
prev = Node(0)
prev.next = self.head
temp = prev
while temp.nextand 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.nextself.head = prev.next
In which case, you can simply call:
thisLList.swapPairsI()
Post a Comment for "Swapping Pairs In A Linked List In Python, One Link Disappears?"