Pairwise swap elements of a linked list by swapping data
Given a singly linked list, write a function to swap elements pairwise.
For example,
- If the linked list is 1->2->3->4->5 then the function should changeit to 2->1->4->3->5, and
- If the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5.
Algorithm:
- Set following pointers
prev = null
node = head
newHead = null
next = null
nextOfNext = null
- Iterate till
node.next != null
next = node.next
nextOfNext = next.next
node.next = node
- if (
prev != null
) thepre.next = next
- if (
newHead == null
) thennewHead = next
prev = node
node = nextOfNext
- Return neHead
Latest Source Code:
Github: ListPairwiseSwap.java
Output:
1 2 2 1 1 2 3 4 5 6 2 1 4 3 6 5 1 2 3 4 5 6 7 2 1 4 3 6 5 7