难度:困难
需要的前置知识:反转一个链表
题目描述
参考代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (k == 1) return head;
ListNode dummy = new ListNode(0);
ListNode beforeRear = dummy;
ListNode p = head;
ListNode pre = null;
while (p != null) {
ListNode curBegin = p;
int cnt = 0;
while (p != null && cnt < k) {
cnt++;
pre = p;
p = p.next;
}
if (cnt == k) {
pre.next = null;
ListNode tNewHead = reverseList(curBegin);
beforeRear.next = tNewHead;
beforeRear = curBegin;
} else {
beforeRear.next = curBegin;
}
}
return dummy.next;
}
private ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)