[LeetCode] 25. Reverse Nodes in k-Group

每k个一组翻转链表。题意是请将input中每K个node进行翻转。这题我暂时只会递归解法,之后想通了迭代怎么写,写的清楚了我再补上。例子

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

思路是用cur指针遍历input,然后用count记录遍历的node个数。因为cur是从head开始的,所以当count === K的时候,cur已经到了第K + 1个node的地方了。此时用递归调用,反转K个node。若不足K个的时候,不会进行翻转。

时间O(n)

空间O(n)

 1 /**
 2  * @param {ListNode} head
 3  * @param {number} k
 4  * @return {ListNode}
 5  */
 6 var reverseKGroup = function(head, k) {
 7     // corner case
 8     if (head === null || head.next === null) {
 9         return head;
10     }
11 
12     // normal case
13     let count = 0;
14     let cur = head;
15     while (cur !== null && count != k) {
16         cur = cur.next;
17         count++;
18     }
19     if (count === k) {
20         cur = reverseKGroup(cur, k);
21         while (count-- > 0) {
22             let next = head.next;
23             head.next = cur;
24             cur = head;
25             head = next;
26         }
27         head = cur;
28     }
29     return head;
30 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/11817279.html