Note: Please note here the nodes are swapped and not the data in the nodes.
Input: DLL = 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6, K = 3
Output: 1 2 4 3 5 6
Third node from the beginning(3) is swapped with third node from the ending(4).
Input: DLL = 1 <-> 2 <-> 3 <-> 4 <-> 5, K = 1
Output: 5 2 3 4 1
Approach: The idea is to traverse to the Kth element from the beginning and Kth node from the ending and change the previous and next pointers. Let K1 be the Kth node from beginning and K2 be Kth node from ending. Then:
- The previous node to K2 has to be changed to the previous node of K1.
- The next node to K2 has to be changed to the next node of K1.
- The previous node to K1 has to be changed to the previous node of K2.
- The next node to K1 has to be changed to the next node of K2.
Below is the implementation of the above approach:
1 4 3 2 5
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Swap Kth node from beginning with Kth node from end in a Linked List
- Delete a node in a Doubly Linked List
- Find the largest node in Doubly linked list
- Delete a Doubly Linked List node at a given position
- Create new linked list from two given linked list with greater element at each node
- Squareroot(n)-th node in a Linked List
- Remove every k-th node of the linked list
- Linked List | Set 3 (Deleting a node)
- Linked List | Set 2 (Inserting a node)
- Remove Nth node from end of the Linked List
- Delete Nth node from the end of the given linked list
- Remove last node of the linked list
- Program for n'th node from the end of a Linked List
- Remove first node of the linked list
- Find the balanced node in a Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Improved By : 29AjayKumar