Leetcode#25 Reverse Nodes in k-Group

原题地址

分两步:

1. 试探。看是否还有k个节点可以翻转

2. 翻转。

[]->[]->[]->[1]->[2]->[3]->[4]->[]->[]->[]->NULL
|------------------|
假设要翻转这一段

翻转前:

head
tail
| |
[]->[]->[]->[1]->[2]->[3]->[4]->[]->[]->[]->NULL
| |
beforeHead afterTail


翻转后:
            tail           head
| |
[]->[]->[]->[4]->[3]->[2]->[1]->[]->[]->[]->NULL
| |
beforeHead afterTail

为了方便处理,在链表首部增加了一个虚拟节点vhead(代码第21行)

代码:

 1 void reverseList(ListNode *head, ListNode *tail) {
 2   ListNode *curr = head;
 3   ListNode *next = head->next;
 4   ListNode *nextNext = NULL;
 5 
 6   while (next != tail) {
 7     nextNext = next->next;
 8     next->next = curr;
 9     curr = next;
10     next = nextNext;
11   }
12 
13   next->next = curr;
14   head->next = NULL;
15 }
16 
17 ListNode *reverseKGroup(ListNode *head, int k) {
18   if (k < 2)
19     return head;
20 
21   ListNode *vhead = new ListNode(0);
22   vhead->next = head;
23   ListNode *tail = NULL;
24   ListNode *beforeHead = vhead;
25   ListNode *afterTail = NULL;
26   int count = 0;
27 
28   while (head) {
29     tail = head;
30     count = k;
31     while (tail && --count)
32       tail = tail->next;
33     if (count)
34       break;
35     afterTail = tail->next;
36 
37     reverseList(head, tail);
38 
39     beforeHead->next = tail;
40     head->next = afterTail;
41 
42     beforeHead = head;
43     head = afterTail;
44   }
45 
46   return vhead->next;
47 }
原文地址:https://www.cnblogs.com/boring09/p/4239913.html