LeetCode25 Reverse Nodes in K Groups

题目描述

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

    解析

    反转链表的进化版本,每K个分成一组进行反转,最后再连起来,递归可解,每次返回反转后的链表头,注意循环条件,如果找不到K个不反转,直接返回原来的序列,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
ListNode start = head;
int count = 1;
while(cur != null){
cur = cur.next;
count++;
if(count == k && cur != null){
ListNode prev = reverseKGroup(cur.next, k);
head = cur;
cur = start;
for(int i = 0; i < k; i++){
ListNode tmp = cur.next;
cur.next = prev;
prev = cur;
cur = tmp;
}
}
}
return head;
}

总结

十分常见的链表题,leetcode 25题老题目了,虽然是hard但是熟记规律也不难掌握,可以多写几遍,这样递归以及反转链表就能掌握得比较透彻了,如果面试问到这题而不会的话是很不应该的。