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

Leetcode | Reverse Nodes in k-Group

时间:2014-05-18 01:53:53      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   c   

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

用了两个指针p1和p2,使得p1和p2相差k-1个位置。每次p1和p2区间reverse一下,然后再把同时更新p1和p2.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3 
 4     void reverse(ListNode *start, ListNode *end) {
 5         ListNode *pre = NULL, *tmp;
 6         while (start != end) {
 7             tmp = start->next;
 8             if (pre) start->next = pre;
 9             pre = start;
10             start = tmp;
11         }
12         end->next = pre;
13     }
14     ListNode *reverseKGroup(ListNode *head, int k) {
15             if (k <= 1) return head;
16             ListNode *p1 = head, *p2 = head, *pre = NULL, *tmp;
17             for (int i = 0; i < k - 1; ++i) {
18                 if (p1 == NULL) return head;
19                 p1 = p1->next;
20             }
21             if (p1 != NULL) head = p1;
22 
23             while (p1 != NULL) {
24                 tmp = p1->next;
25                 if (pre) pre->next = p1;
26                 reverse(p2, p1);
27                 pre = p2; // the tail of previous k-list
28                 p2 = p1 = tmp; // update p2
29                 for (int i = 0; i < k - 1; ++i) {
30                     if (p1 == NULL) {
31                         break; 
32                     }
33                     p1 = p1->next;
34                 }
35                 if (p1 == NULL) pre->next = tmp; // the left part is less than k
36             }
37 
38             return head;
39         }
40 };
bubuko.com,布布扣

一开始想一遍走完,边走边reverse,但是太复杂了,所以还是这样吧。。。

Leetcode | Reverse Nodes in k-Group,布布扣,bubuko.com

Leetcode | Reverse Nodes in k-Group

标签:des   style   blog   class   code   c   

原文地址:http://www.cnblogs.com/linyx/p/3733980.html

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