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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值