Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

K个一组翻转链表

来源Leetcode第25题K个一组翻转链表

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

k = 2 时,应当返回: 2->1->4->3->5

k = 3 时,应当返回: 3->2->1->4->5

说明 :

  • 你的算法只能使用常数的额外空间。
  • 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

最简单的思路,把K个结点压入栈中,然后出栈的顺序就是翻转后的顺序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null || k == 0 || k == 1)
return head;
Stack<ListNode> stack = new Stack<>();
ListNode ahead = new ListNode(0);
ListNode p1 = ahead,p2;
while(true){
int count = 0;
p2 = head;
while(p2 != null && count < k){
stack.add(p2);
p2 = p2.next;
count++;
}
if(count != k){
p1.next = head;
break;
}
while(!stack.isEmpty()){
p1.next = stack.pop();
p1 = p1.next;
}
p1.next = p2;
head = p2;
}
return ahead.next;
}

尾插法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
pre
tail head
dummy 1 2 3 4 5
# 我们用tail 移到要翻转的部分最后一个元素
pre head tail
dummy 1 2 3 4 5
cur
# 我们尾插法的意思就是,依次把cur移到tail后面
pre tail head
dummy 2 3 1 4 5
cur
# 依次类推
pre tail head
dummy 3 2 1 4 5
cur
....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next == null || k == 0 || k == 1)
return head;
ListNode ahead = new ListNode(0);
ahead.next = head;
ListNode pre = ahead,tail,tmp;
while(true){
int count = 0;
tail = head;
while(tail != null && count < k){
tail = tail.next;
count++;
}
if(tail == null)
break;
tmp = pre.next;
while(pre.next != tail){
ListNode cur = pre.next; // cur = 2
pre.next = cur.next; //1 -> 3
cur.next = tail.next; //2 -> k + 1
tail.next = cur; //k -> 2
}
pre = tmp;
tail = tmp;
}
return ahead.next;
}

翻转链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode end = dummy;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) end = end.next;
if (end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}

private ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}