LeetCode 25: Reverse Nodes in k-Group
Problem Description
Given the head
of a linked list, reverse the nodes of the list k
at a time, and return the 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.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Follow-up: Can you solve the problem in O(1)
extra memory space?
Solution
There are not much tricks here, but we need to divide and solve sub-problems. The first is to reverse a linked-list, the second is to properly connecting nodes between the k-reversed linked-lists, especially with the constant space complexity. Of course, we have to first check whether there are k
nodes before reversing it.
Java Code
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if( k==1 ) return head;
ListNode prev_node = new ListNode(), test = head, curr=prev_node;
while( true ){
int i=0;
test = head;
while( test!=null && i<k){
test = test.next;
i++;
}
if(i < k){
curr.next = head;
break;
}
i = 1;
ListNode second_node = head.next;
test = head;
while(i++ < k){
ListNode tmp = second_node.next;
second_node.next = test;
test = second_node;
second_node = tmp;
}
curr.next = test;
curr = head;
head = second_node;
}
return prev_node.next;
}
}
The post is published under CC 4.0 License.