Reverse Nodes in k-Group
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.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(k <= 1) return head;
if(head == null) return head;
ListNode start = head;
ListNode cur = head;
ListNode end;
for(int i = 1; i < k; i ++){
if(cur.next == null){
// reverseLinkedlist(start, cur);
// return cur;
return head;
}
cur = cur.next;
}
ListNode next = cur.next;
reverseLinkedlist(start, cur);
ListNode newHead = cur;
// Go on
if(next == null) return newHead;
start = next;
cur = next;
ListNode prev = head;
while(true){
for(int i = 1; i < k; i ++){
if(cur.next == null){
// reverseLinkedlist(start, cur);
prev.next = start;
return newHead;
}
cur = cur.next;
}
next = cur.next;
reverseLinkedlist(start, cur);
prev.next = cur;
prev = start;
if(next != null){
cur = next;
start = next;
}
else{
return newHead;
}
}
}
public void reverseLinkedlist(ListNode start, ListNode end){
if(start == null) return;
if(start == end) return;
if(start.next == end) {
end.next = start;
start.next = null;
return;
}
ListNode prev = start;
ListNode cur = start.next;
ListNode next = cur.next;
while(next != end){
cur.next = prev;
prev = cur;
cur = next;
next = next.next;
}
next.next = cur;
cur.next = prev;
start.next = null;
}
}