/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || k ==1){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode next = head;
ListNode prev = dummy;
int count = 0;
while(next!=null){
next = next.next;
count++;
if(count == k){
prev= reverse(prev, next);
count = 0;
}
}
return dummy.next;
}
private static ListNode reverse(ListNode prev, ListNode next){
ListNode last = prev.next;
ListNode cur = last.next;
while(cur!=next){
last.next = cur.next;
cur.next = prev.next;
prev.next = cur;
cur = last.next;
}
return last;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// head - head-pointer to direct part,
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
head.next = curr; // preappending "direct" head to the reversed list
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
head = curr;
}
return head;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1), pre = dummy,b egin = head;
dummy.next = head;
int i = 0; // count the ordinal number of the node
while (head != null) {
i++;
if (i % k == 0) {
ListNode nextBegin = head.next; // store the next begin point
reverse(begin, head); // reverse the begin node to the cur node
pre.next = head; // restore the given k nodes to the original link
pre = begin; // jump k nodes
begin = nextBegin;
head = begin;
} else {
head = head.next;
}
}
return dummy.next;
}
private void reverse(ListNode start, ListNode end) {
while (start != end) {
ListNode next = start.next;
start.next = end.next;
end.next = start;
//end = start;
start = next;
}
}
}