码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode25 Reverse Nodes in k-Group

时间:2016-08-15 20:33:04      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

题意:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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)

分析:

题目意思是每k个链表进行翻转,不足k个保持不变。

可以写一个翻转k个节点的辅助函数,然后在原函数中判断后续是否有k个节点,以及后续节点位置。

注意事项见代码注释。

代码:

 1 class Solution {
 2 private:
 3     ListNode* reverseKelement(ListNode* head, int k) {
 4         ListNode* result = nullptr;
 5         for (int i = 0; i < k; ++i) {
 6             ListNode* temp = head -> next;
 7             head -> next = result;
 8             result = head;
 9             head = temp;
10         }
11         return result;
12     }
13 public:
14     ListNode* reverseKGroup(ListNode* head, int k) {
15         if (head == nullptr) {
16             return head;
17         }
18         ListNode dummy(0);
19         dummy.next = head;
20         head = &dummy;
21         
22         ListNode* runner = head -> next;
23         int flag = 1;
24         for (int i = 0; i < k; ++i) {
25             if (runner -> next != nullptr || (runner -> next == nullptr && k == i + 1) ) { //恰好k个到结尾情况没考虑, 例如[1,2] 2情况
26                 runner = runner -> next;
27             }
28             else {
29                 flag = 0;
30                 break;
31             }
32         }
33         while (flag == 1) {
34             ListNode* temp1 = head -> next;
35             head -> next = reverseKelement(temp1, k);
36             temp1 -> next = runner;
37             head = temp1;
38             for (int i = 0; i < k; ++i) {
39                 if (runner != nullptr && (runner -> next != nullptr || (runner -> next == nullptr && k == i + 1)) ) { //对应添加runner !=  nullptr
40                     runner = runner -> next;
41                 }
42                 else {
43                     flag = 0;
44                     break;
45                 }
46             }
47         }
48         return dummy.next;
49     }
50 };

 

 

LeetCode25 Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5774082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!