Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most of the compilers).
The problem seems simple at first look, but it has many interesting cases.
Let X be the kth node from beginning and Y be the kth node from end. Following are the interesting cases that must be handled.
1) Y is next to X
2) X is next to Y
3) X and Y are same
4) X and Y don’t exist (k is more than number of nodes in linked list)
Original Linked List: 1 2 3 4 5 6 7 8 Modified List for k = 1 8 2 3 4 5 6 7 1 Modified List for k = 2 8 7 3 4 5 6 2 1 Modified List for k = 3 8 7 6 4 5 3 2 1 Modified List for k = 4 8 7 6 5 4 3 2 1 Modified List for k = 5 8 7 6 4 5 3 2 1 Modified List for k = 6 8 7 3 4 5 6 2 1 Modified List for k = 7 8 2 3 4 5 6 7 1 Modified List for k = 8 1 2 3 4 5 6 7 8
Please note that the above code runs three separate loops to count nodes, find x and x prev, and to find y and y_prev. These three things can be done in a single loop. The code uses three loops to keep things simple and readable.
Thanks to Chandra Prakash for initial solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum cost path from source node to destination node via an intermediate node
- Squareroot(n)-th node in a Linked List
- Linked List | Set 3 (Deleting a node)
- Remove last node of the linked list
- Remove every k-th node of the linked list
- Linked List | Set 2 (Inserting a node)
- Program for n'th node from the end of a Linked List
- Remove first node of the linked list
- Reverse each word in a linked list node
- Find first node of loop in a linked list
- Delete every Kth node from circular linked list
- Delete a node in a Doubly Linked List
- Delete a Linked List node at a given position
- Write a function to get Nth node in a Linked List
- Insert node into the middle of the linked list