I am trying to solve swap node in pairs (linked list). I have the correct code, but I am stucked while interpreting swapping step.
here is the code:
def swapPairs(head):
pre = ListNode(0)
pre.next = head
while pre.next and pre.next.next:
a = pre.next
b = a.next
pre.next, b.next, a.next = b, a, b.next
pre = a
return pre.next
for example, if my linked list is 1->2->3->4. Initially a is pointing to 1, and b to 2. During the swapping step: how do we not lose the linked list after 2? because b.next will point to a before we actually do a.next = b.next?
You have to preserve starting node of next pair as well as last node of the list reversed so far. I don't code in python so I can provide an algorithm to achieve what you are looking for. You can check following