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

Leetcode 25 Reverse Nodes in K-Group

时间:2015-04-14 09:48:49      阅读:104      评论: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

 

思路: 

一: 该题可以参考 swap nodes in pairs 和 reverse link list. 利用 three pointers(pre, start,then)的方法来解决,统计一个有多少个group,最后一个group不进行任何变化 。 

二: 可以用递归的方法。

就是 每k下,递归一次,然后k后面那个next正常走,k内调用recursive. 注意递归内的开始的初始条件判断,让其好返回回来。 

 

 1 class Solution {
 2 public:
 3     ListNode *reverseKGroup(ListNode *head, int k)
 4     {
 5         
 6         if(head == NULL || head->next == NULL || k<2)
 7             return head; 
 8         
 9         ListNode * fakeNode = new ListNode(0);
10         fakeNode -> next = head; 
11         ListNode * p = head; 
12         int length = 0;
13         while(p)
14         {
15             length++;
16             p = p->next; 
17         }
18         if(k>length)
19             return fakeNode->next; 
20         ListNode * pre = fakeNode;
21         ListNode * start = pre->next; 
22         ListNode * then = start ->next;
23 
24         int total = 0;
25         int cnt = 0;
26         while(then!=NULL)
27         {
28             while(cnt!=k-1 && then)
29             {
30                 cnt ++;
31                 start->next = then->next; 
32                 then->next = pre->next; 
33                 pre->next = then; 
34                 then = start->next; 
35             }
36             total ++;
37             if(total == length/k)
38                 break;
39             pre = start; 
40             start = pre->next; 
41             then = start->next; 
42             cnt =0;
43         }
44         return fakeNode->next; 
45     }
46 };

 

Leetcode 25 Reverse Nodes in K-Group

标签:

原文地址:http://www.cnblogs.com/zhuguanyu33/p/4423936.html

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