25.reverse-nodes-in-k-groups-en
Problem
https://leetcode.com/problems/reverse-nodes-in-k-group/
Problem Description
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
nullFor 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
countkeep track linked list counts when traverse linked listUse
startto keep track each group start node position.Use
endto keep track each group end node positionReverse(
k nodes)AKA:(start, end) - start and end exclusively.After reverse, update
startpoint to reversed group last node.If
counts % k != 0, thenendmove 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 nodeto solve linked list problem, because head node may be changed during operation. for example: herehead updated from 1->3, anddummy (List(0))keep the same.
Complexity Analysis
Time Complexity:
O(n) - n is number of Linked ListSpace 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
return
dummy.next.
Code (Java/Python3)
Java/Python3)Java Code
Python3 Cose
References
Extension
Require from right to left reverse nodes in k groups. (ByteDance Interview)
Example,
1->2->3->4->5->6->7->8, k = 3,From right to left, group as
k=3:6->7->8reverse to8->7->6,3->4->5reverse to5->4->3.1->2only has 2 nodes, which less thank=3, do nothing.return:
1->2->5->4->3->8->7->6
Here, we pre-process linked list, reverse it first, then using Reverse nodes in K groups solution:
Reverse linked list
From left to right, reverse linked list group as k nodes.
Reverse step #2 linked list
For example:1->2->3->4->5->6->7->8, k = 3
Reverse linked list:
8->7->6->5->4->3->2->1Reverse nodes in k groups:
6->7->8->3->4->5->2->1Reverse step#2 linked list:
1->2->5->4->3->8->7->6
Similar Problems
Last updated
Was this helpful?