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

Reverse Nodes in k-Group

时间:2014-10-26 15:30:30      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   sp   div   on   

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

 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 == NULL)
13             return head;
14         ListNode *p,*q,*r;
15         int i = 0;
16         p = head;
17         while (p)
18         {
19             p = p->next;
20             i++;
21         }
22         if (k > i)
23             return head;
24         i = 1;
25         p = head;
26         q = p->next;
27         if (q)
28             r = q->next;
29         while (i < k && q)
30         {
31             q->next = p;
32             p = q;
33             q = r;
34             if (q)
35                 r = q->next;
36             i++;
37         }
38         head->next = reverseKGroup(q,k);
39         head = p;
40         return head;
41     }
42 };

 

Reverse Nodes in k-Group

标签:des   style   blog   color   io   for   sp   div   on   

原文地址:http://www.cnblogs.com/george-cw/p/4051999.html

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