public static ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current != null && current.next != null) {
ListNode mostleft = current.next;
ListNode mostright = mostleft;
// 获取最右端节点
int i;
for (i = k - 1; i > 0; i--) {
if (mostright.next == null) {
break;
}
mostright = mostright.next;
}
// 剩下的节点不够反转
if (i > 0)
break;
ListNode next = mostright.next;
// mostleft到mostright的反转
ListNode innerPre = null;
ListNode innerCur = mostleft;
while (innerCur != next) {
ListNode innerNext = innerCur.next;
innerCur.next = innerPre;
innerPre = innerCur;
innerCur = innerNext;
}
current.next = mostright;
mostleft.next = next;
current = mostleft;
}
return dummy.next;
}
递归写法:
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
for (int i = 0; i < k; i++) {
//剩余数量小于k的话,则不需要反转。
if (tail == null) {
return head;
}
tail = tail.next;
}
// 反转前 k 个元素
ListNode newHead = reverse(head, tail);
//下一轮的开始的地方就是tail
head.next = reverseKGroup(tail, k);
return newHead;
}
private ListNode reverse(ListNode head, ListNode tail) {
ListNode pre = null;
ListNode next = null;
while (head != tail) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}