zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    hdu 5918(强行水过去..正解KMP)
    hdu 5914(斐波拉契数列)
    hdu 5912(迭代+gcd)
    bzoj 2819(DFS序+树状数组+博弈+lca)
    BestCoder #88(1001 1002)
    hdu 5468(dfs序+容斥原理)
    hdu 5692(dfs序+线段树,好题)
    dfs序题目练习
    csu 1806 & csu 1742 (simpson公式+最短路)
    LuoGuP3774:[CTSC2017]最长上升子序列
  • 原文地址:https://www.cnblogs.com/boring09/p/4239913.html
Copyright © 2011-2022 走看看