Star

LeetCode 25. Reverse Nodes in k-Group

Question

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example, Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Explanation

这道题和之前的reverse nodes II很像,有一个范围,你要写一个reverse函数去在这个范围内reverse一下linked list。 其他不难,主要还是想清楚翻转的过程。

Code

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
31
32
33
34
35
36
public class Solution {
private static ListNode reverse(ListNode pre, ListNode next){
ListNode last = pre.next;
ListNode cur = last.next;
while (cur != next) {
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
return last;
}
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k== 1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
int count = 0;
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
count ++;
ListNode next = cur.next;
if (count == k) {
pre = reverse(pre, next);
count = 0;
}
cur = next;
}
return dummy.next;
}
}