Given a singly linked list, write a function to swap elements pairwise.
Input : 1->2->3->4->5->6->7 Output : 2->1->4->3->6->5->7, Input : 1->2->3->4->5->6 Output : 2->1->4->3->6->5
A solution has been discussed set 1. Here a simpler solution is discussed. We explicitly change pointers of first two nodes, then fix remaining nodes.
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7 Linked list after calling pairWiseSwap() 2 1 4 3 6 5 7
The approach here is to use the double pointers so that we need not update the head pointer during swap separately.
Actual List: 1 2 3 4 5 6 ModifiedLinked List: 2 1 4 3 6 5
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Pairwise swap elements of a given linked list by changing links
- Pairwise swap elements of a given linked list
- Swap nodes in a linked list without swapping data
- Check if a Linked List is Pairwise Sorted
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- In-place Merge two linked lists without changing links of first list
- Sort a linked list of 0s, 1s and 2s by changing links
- Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
- Sorted insert in a doubly linked list with head and tail pointers
- Update adjacent nodes if the current node is zero in a Singly Linked List
- Delete N nodes after M nodes of a linked list
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Swap Kth node from beginning with Kth node from end in a Linked List
- Swap the vowels in the linked list representation of a string
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.