Given a linked list and an integer M, the task is to append the last M nodes of the linked list to the front.
Input: List = 4 -> 5 -> 6 -> 1 -> 2 -> 3 -> NULL, M = 3
Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
Input: List = 8 -> 7 -> 0 -> 4 -> 1 -> NULL, M = 2
Output: 4 -> 1 -> 8 -> 7 -> 0 -> NULL
Approach: Find the first node of the last M nodes in the list, this node will be the new head node so make the next pointer of the previous node as NULL and point the last node of the original list to the head of the original list. Finally, print the updated list.
Below is the implementation of the above approach:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL
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.
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Given a linked list, reverse alternate nodes and append at the end
- Swap Kth node from beginning with Kth node from end in a Linked List
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Find the product of last N nodes of the given Linked List
- Find the sum of last n nodes of the given Linked List
- Exchange first and last nodes in Circular Linked List
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Double elements and append zeros in linked list
- Delete N nodes after M nodes of 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
- Create new linked list from two given linked list with greater element at each node
- Move last element to front of a given Linked List | Set 2
- Move last m elements to the front of a given Linked List
- Move last element to front of a given Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
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.