题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (k == 1) {
return head;
}
int c = 0;
ListNode aHead = null, aTail = null, next = head, start = head;
while(next != null) {
c++;
if (c == k) {
ListNode end = start, aNext = end.next, tmp;
while(start != next) {
tmp = aNext.next;
aNext.next = start;
end.next = tmp;
start = aNext;
aNext = end.next;
}
if (aHead == null) {
aHead = start;
}
if (aTail != null) {
aTail.next = start;
}
aTail = end;
next = start = aNext;
c = 0;
} else {
next = next.next;
}
}
return aHead == null ? head : aHead;
}
}


