zoukankan      html  css  js  c++  java
  • LeetCode-Reverse Nodes in k-Group

    繁琐的链表操作,很开心,一次就过了,不过推敲的时间也有20分钟了,

    还是加快思考的速度。

     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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL || k <= 1) {
    15             return head;
    16         }       
    17         ListNode *first = getKNode(head, k);
    18         if (first == head) {
    19             return head;
    20         }
    21         ListNode *res = first;
    22         ListNode *start = first->next;
    23         reverse(head, first);
    24         ListNode *pre = head;
    25         while (start) {
    26             first = getKNode(start, k);
    27             if (first == start) {
    28                 pre->next = start;
    29                 return res;
    30             }
    31             pre->next = first;
    32             pre = start;
    33             ListNode *temp = first->next;
    34             reverse(start, first);
    35             start = temp;
    36         }
    37         if (start == NULL) {
    38             pre->next = NULL;
    39             return res;
    40         }
    41         return res;
    42     }
    43     ListNode *getKNode(ListNode *head, int k) {
    44         ListNode *first = head;
    45         int count = 1;
    46         while (first->next && count < k) {
    47             first = first->next;
    48             ++count;
    49         }
    50         if (first->next == NULL && count < k) {
    51             return head;
    52         }
    53         return first;
    54     } 
    55     void reverse(ListNode *start, ListNode *end) {
    56         ListNode *pre = start;
    57         ListNode *iter = start->next;
    58         while (iter != end) {
    59             ListNode *temp = iter->next;
    60             iter->next = pre;
    61             pre = iter;
    62             iter = temp;
    63         }
    64         end->next = pre;
    65     }
    66 };
  • 相关阅读:
    网站实时信息采集和统计graphite
    内存检查工具Valgrind
    usr/bin/ld: cannot find 错误解决方法和 /etc/ld.so.conf
    通用makefile
    关于/proc/进程idpid/fd ,根据fd来查找连接
    boost enable_shared_from_this
    cdll和windll的差别
    一些项目——空白格式化
    Session笔记
    黑马程序猿_7K面试题之交通灯系统
  • 原文地址:https://www.cnblogs.com/chasuner/p/reversekgroup.html
Copyright © 2011-2022 走看看