DSA, linked list, swap nodes

56 views Asked by At

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?

1

There are 1 answers

0
kriti On

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

1. newHead=null
2. previousNode=null
3. while head is not null : // While loop start
      curr = head.next;
      if curr is not null:  // If block
         next= curr.next
         curr.next=head
         head.next=null
      else:
         next=head
                         //If-else block ends here
      
      if prevNode is not null:  // Another if block
         prevNode.next=curr
                                // If block ends here

      prevNode=head
    
      if newNode is null :  // another if block
         newNode=curr
                          // if block ends here
    
      head=next
                        // while loop ends here

4. return newHead         // return head of reversedList