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
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.
- Swap Kth node from beginning with Kth node from end in a Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Difference between Singly linked list and Doubly linked list
- Append the last M nodes to the beginning of the given linked list
- Construct a Doubly linked linked list from 2D Matrix
- 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
- Recursive Approach to find nth node from the end in the linked list
- Delete Nth node from the end of the given linked list
- Remove Nth node from end of the Linked List
- Program for n'th node from the end of a Linked List
- Create new linked list from two given linked list with greater element at each node
- Memory efficient doubly linked list
- Convert a given Binary Tree to Doubly Linked List | Set 1
- QuickSort on Doubly Linked List
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Convert a given Binary Tree to Doubly Linked List | Set 3
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