LeetCode 25. K 个一组翻转链表
原题链接
困难
作者:
LangB
,
2020-10-28 18:20:57
,
所有人可见
,
阅读 305
迭代法
/**
* 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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
while (true) {
ListNode q = p;
// 统计是否存在链表后面是否存在k个节点
for (int i = 0; i < k && q != null; i++) {
q = q.next;
}
// 如果不足K个,则跳出循环
if (q == null) {
break;
}
ListNode a = p.next, b = a.next;
// 这k个节点内部反转
for (int i = 0; i < k - 1; i++) {
ListNode c = b.next;
b.next = a;
a = b;
b = c;
}
// 外部反转拼接
ListNode c = p.next;
p.next = a;
c.next = b;
p = c;
}
return dummy.next;
}
}
递归法
/**
* 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 (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 prev = null;
ListNode next = null;
while (head != tail) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
- 时间复杂度 O(n)
- 空间复杂度 O(n / k),递归所需空间