解法一:利用循环,无递归
时间复杂度O(KlogN) 空间复杂度O(1)
java描述:
public ListNode reverseKGroup(ListNode head, int k) {
int n = 0;
for(ListNode i = head; i != null; n++, i = i.next);
ListNode dummy = new ListNode(0);
dummy.next = head;
for(ListNode pre = dummy, tail = head; n >= k; n -= k) {
for (int i = 1; i < k; i++) {
ListNode next = tail.next.next;
tail.next.next = pre.next;
pre.next = tail.next;
tail.next = next;
}
pre = tail;
tail = tail.next;
}
return dummy.next;
}
javaScript描述:
var reverseKGroup = function(head, k) {
let n = 0;
for (let i = head; i != null; i = i.next, n++);
let dummy = new ListNode(0);
dummy.next = head;
for (let pre = dummy, tail = head; n >= k; n-=k) {
for (let i = 1; i < k; i++) {
let next = tail.next.next;
tail.next.next = pre.next;
pre.next = tail.next;
tail.next = next;
}
pre = tail;
tail = tail.next;
}
return dummy.next;
};
代码的核心是
for (int i = 1; i < k; i++) {
ListNode next = tail.next.next;
tail.next.next = pre.next;
pre.next = tail.next;
tail.next = next;
}
pre = tail;
tail = tail.next;
当k为2时翻转1次,k为3在2的基础上再翻转一次
我们假设K为3
翻转第一次
翻转第二次
解法二:递归
最坏时间复杂度O(N) 空间复杂度O(N)
大神的代码,时间复杂度跑的很牛逼啊,虽然题目规定不能用额外的空间,不理解的话,自己画一遍图就行了
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
int count = 0;
while (cur != null && count != k) {
cur = cur.next;
count++;
}
if (count == k) {
cur = reverseKGroup(cur, k);
while (count-- > 0) {
ListNode temp = head.next;
head.next = cur;
cur = head;
head = temp;
}
head = cur;
}
return head;
}
javaScript描述:
var reverseKGroup = function(head, k) {
let count = 0;
let cur = head;
while (cur != null && count != k) {
cur = cur.next;
count++;
}
if (count === k) {
cur = reverseKGroup(cur, k);
while (count-- > 0) {
let temp = head.next;
head.next = cur;
cur = head;
head = temp;
}
head = cur;
}
return head;
};