[LeetCode] Reverse Nodes in kGroup

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

写一个逆转链表的函数,找出kgroup的头和尾逆转,直到结尾。

 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 struct Node
10 {
11     ListNode *beg;
12     ListNode *end;
13     Node(){}
14     Node(ListNode *b, ListNode *e):beg(b), end(e){}
15 };
16 
17 class Solution {
18 public:
19     Node reverse(ListNode *beg, ListNode *end)
20     {
21         ListNode *pPre = NULL;
22         ListNode *p = beg;
23         
24         while(p != end)
25         {
26             ListNode *pNext = p->next;
27             p->next = pPre;
28             pPre = p;
29             p = pNext;
30         }
31         
32         p->next = pPre;
33         
34         return Node(end, beg);
35     }
36     
37     ListNode *reverseKGroup(ListNode *head, int k) {
38         // Start typing your C/C++ solution below
39         // DO NOT write int main() function
40         if (head == NULL)
41             return NULL;
42         
43         ListNode *pPre = NULL;  
44         ListNode *p = head;
45         while(p)
46         {
47             ListNode *q = p;
48             for(int i = 0; i < k - 1; i++)
49             {
50                 q = q->next;
51                 if (q == NULL)
52                     return head;
53             }
54             
55             ListNode *qNext = q->next;
56             
57             Node ret = reverse(p, q);
58             if (pPre)
59                 pPre->next = ret.beg;
60             else
61                 head = ret.beg;
62             ret.end->next = qNext;
63             pPre = ret.end;
64             p = qNext;
65         }
66         
67         return head;
68     }
69 };
原文地址:https://www.cnblogs.com/chkkch/p/2776086.html