野原新之助0

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

https://leetcode.com/problems/reverse-nodes-in-k-group/description/

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

 

这道题综合了LinkedList中 Iter + recur的内容:

  1. Recursion: post order. 通过recursion来进行每K个的判断, 每次返回的都是下一层的head, 也就是指向当前层k+1的指针. 其中还通过count计数器来判断了最后一层若不够k个的时候的情况.
  2. Iteration: post process部分(9-19行), 内容和reverse linkedlist一样, 考验基础知识的灵活运用.
  3. Note: 运用count计数器来作为各种判断条件, 比指针判断要优雅, 也少了很多corner case.

代码思路:

  • sanity check
  • while循环, 找下一层的head, 也就是当前层的第k+1个node, 且同时加入count != k的判断来处理最后一节儿不够k个node的情况.
  • if 判断 count == k, 接上一段儿, 若不够k个将不会进行 if 条件的内部, 处理最后一段儿. if 条件的内部是核心
  • 内部:
  1. 第一句是recursion, 传入的是下一层的head, 也就是之前找到的第 k+1 个节点. 返回的还是下一层的head, 所以这行代码执行完之后的curr变成了新的下层head(KEY, 这句话必须理解).
  2. 第二句之后的while循环是将当前层的k个nodes进行reverse. 内容是经典reverse linkedlist的iter版. 不难

 

 1     public ListNode reverseKGroup(ListNode head, int k) {
 2         if (head == null || head.next == null) return head;
 3         int count = 0;
 4         ListNode curr = head, prev = head, temp = null;
 5         while (curr != null && count != k) {
 6             curr = curr.next;
 7             count++;
 8         }
 9         if (count == k) {
10             curr = reverseKGroup(curr, k);
11             while (count > 0) {
12                 temp = prev.next;
13                 prev.next = curr;
14                 curr = prev;
15                 prev = temp;  
16                 count--;
17             }
18             return curr;
19         }
20         return head;
21     }

 

posted on 2018-03-25 08:21  野原新之助0  阅读(93)  评论(0编辑  收藏  举报