Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
Solution
Traverse linked list from left to right, during traverse, group nodes in k, then reverse each group. How to reverse a linked list given start, end node?
Reverse linked list:
Initial a prev node null
For each move, use temp node to keep current next node.
During traverse, update current node pointing to previous node, update previous pointing to current node
Update current to temp
For example(as below pic): reverse the whole linked list 1->2->3->4->null -> 4->3->2->1->null
Here Reverse each group(k nodes):
First group, use count keep track linked list counts when traverse linked list
Use start to keep track each group start node position.
Use end to keep track each group end node position
Reverse(k nodes)AKA: (start, end) - start and end exclusively.
After reverse, update start point to reversed group last node.
If counts % k != 0, then end move to next(end=end.next), for each movecount+1.
As below pic show steps 4 and 5, reverse linked list in range (start, end):
For example(as below pic),head=[1,2,3,4,5,6,7,8], k = 3
NOTE: Usually we create a dummy node to solve linked list problem, because head node may be changed during operation. for example: here head updated from 1->3, and dummy (List(0)) keep the same.
Complexity Analysis
Time Complexity:O(n) - n is number of Linked List
Space Complexity:O(1)
Key Points
create a dummy node, dummy = ListNode(0)
Group linked list as k=3, keep track of start and end node for each group.
Reverse each group, update start and end node references