Problem Statement:
Iterative Pair swap the elements of the Linked List
Source Code
Solution:
We require minimum of three pointers. I have used 'temp' for moving forward. 'back' pointer points to the next of 'front' pointer.'front' is the leading pointer which then later connects to 'back'.
Below is the Iterative Implementation:
Please comment and post if any better or efficient approach available may be with lesser pointers.
Happy Coding !! :)
Iterative Pair swap the elements of the Linked List
Source Code
Solution:
We require minimum of three pointers. I have used 'temp' for moving forward. 'back' pointer points to the next of 'front' pointer.'front' is the leading pointer which then later connects to 'back'.
Below is the Iterative Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Iterative Subroutine to swap pairs of nodes of linked list * @return new Head of the linked list */ public Node pairSwap(Node head){ Node temp=head; head=head.next; //new head Node front,back; while(temp!=null && temp.next!=null) { back=temp; front=temp.next; back.next=front.next; front.next=back; if(temp.next!=null) temp=temp.next; if(temp.next!=null) back.next=temp.next; } return head; } |
Please comment and post if any better or efficient approach available may be with lesser pointers.
Happy Coding !! :)