Given pointer to the head node of a linked list and a number K, the task is to reverse the first K nodes of the linked list. We need to reverse the list by changing links between nodes.
check also Reversal of a linked list
Input : 1->2->3->4->5->6->7->8->9->10->NULL k = 3 Output :3->2->1->4->5->6->7->8->9->10->NULL Input :10->18->20->25->35->NULL k = 2 Output :18->10->20->25->35->NULL
Explanation of the method:
suppose linked list is 1->2->3->4->5->NULL nad k=3
1) Traverse the linked list till K-th point.
2) Break the linked list in to two parts from k-th point. After partition linked list will look like 1->2->3->NULL & 4->5->NULL
3) Reverse first part of the linked list leave second part as it is 3->2->1->NULL and 4->5->NULL
4) Join both the parts of the linked list, we get 3->2->1->4->5->NULL
A pictorial representation of how the algorithm works
Given list 1 2 3 4 5 Modified list 3 2 1 4 5
Time Complexity : O(n)
- Can we reverse a linked list in less than O(n)?
- Reverse a linked list
- Reverse a Doubly Linked List | Set-2
- Reverse a circular linked list
- Reverse a Linked List according to its Size
- Reverse a Doubly Linked List
- Reverse a sublist of linked list
- Reverse a Linked List in groups of given size | Set 2
- Java Program for Reverse a linked list
- Reverse a doubly circular linked list
- Program to reverse a linked list using Stack
- Print reverse of a Linked List without actually reversing
- Reverse a Linked List in groups of given size | Set 1
- Reverse each word in a linked list node
- Reverse a Doubly linked list using recursion
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.