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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Double elements and append zeros in linked list
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- 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
- Delete N nodes after M nodes of a linked list
- Linked List Sum of Nodes Between 0s
- Sum of the alternate nodes of linked list
- Sum of all distinct nodes in a linked list
- Find the sum of last n nodes of the given Linked List
- Linked List Product of Nodes Between 0s
- Sum and Product of all the nodes which are less than K in the linked list
- Sum of all odd frequency nodes of the Linked List
- Find sum of even and odd nodes in a linked list
- Segregate even and odd nodes in a Linked List
- Sum of the nodes of a Singly Linked List
- Sum of the nodes of a Circular Linked List
- Replace nodes with duplicates in 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 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.