LeetCode 25. Reverse Nodes in k-Group

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

 

Hard难度的题目,果然还是有一些复杂的,不过今天下午我在没有任何参考的情况下独自写出来了,还是很开心的,前两天的复习与思考没有白费。

言归正传,这道题和之前那一道Swap Nodes in Pairs非常相似,只是这次翻转不是2个一组,而是一次翻转k个,复杂度高一些,但是思路没变,做链表的题目一定要自己先去画图,对着图分析,会简单很多。这道题我先建立一个虚拟节点放在头结点之前,这样一来会增加一些内存开销,但是方便之处在于不需要单独考虑头结点的翻转,大大简化了整个过程。而且我们注意到,一组k个节点,只需要移动k-1次,就可以完成全部的翻转。pre指针指向需要翻转的k个节点中第一个节点,cur指针指向待移动的节点的前一个节点,while中的for循环每执行一次,将cur指向的下一个节点插入到pre之后,执行k-1次,完成本组k个节点的翻转,代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseKGroup(ListNode* head, int k) {
12         if (head == nullptr || k <= 1)
13             return head;
14         ListNode *dummy = new ListNode(-1);
15         ListNode *pre = dummy, *cur = pre;
16         dummy->next = head;  //引入虚拟头结点
17         int num = 0;
18         while (cur->next)
19         {
20             num++;
21             cur = cur->next;
22         }
23         while (num / k)  //每k个算是一趟,这里控制的是整体的趟数  while(num >= k)
24         {
25             cur = pre->next;
26             for (int i = 1; i < k; i++)
27             {
28                 ListNode *t = cur->next;
29                 cur->next = t->next;
30                 t->next = pre->next;
31                 pre->next = t;
32             }
33             pre = cur;
34             num -= k;
35         }
36         return dummy->next;
37     }
38 };

时间复杂度:O(n)

空间复杂度:O(1)

 

一刷:AC

posted @ 2018-01-04 16:14  皇家大鹏鹏  阅读(125)  评论(0编辑  收藏  举报