zoukankan      html  css  js  c++  java
  • leetcode25 K个一组翻转链表

    思路:

    模拟。

    实现:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode() : val(0), next(nullptr) {}
     7  *     ListNode(int x) : val(x), next(nullptr) {}
     8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     9  * };
    10  */
    11 class Solution
    12 {
    13 public:
    14     ListNode* reverse(ListNode* head)
    15     {
    16         if (head == NULL or head->next == NULL) return head;
    17         ListNode* pre = head, *cur = head->next;
    18         head->next = NULL;
    19         while (cur)
    20         {
    21             ListNode* nxt = cur->next;
    22             cur->next = pre;
    23             pre = cur;
    24             cur = nxt;
    25         }
    26         return pre;
    27     }
    28     ListNode* reverseKGroup(ListNode* head, int k)
    29     {
    30         ListNode* cur = head, *cur_head = head, *res = NULL, *last_tail = NULL;
    31         int cnt = 1;
    32         while (cur)
    33         {
    34             if (cnt % k == 0)
    35             {
    36                 ListNode* next_head = cur->next;  
    37                 cur->next = NULL;
    38                 ListNode* new_head = reverse(cur_head);
    39                 if (res == NULL) res = new_head;
    40                 if (last_tail) last_tail->next = new_head; 
    41                 cur_head->next = next_head;
    42                 last_tail = cur = cur_head;
    43                 cur_head = cur->next;
    44             }
    45             cnt++;
    46             cur = cur->next;
    47         }
    48         return res ? res: head;
    49     }
    50 };
  • 相关阅读:
    MySQL使用alter修改表的结构
    MySQL基本库表管理
    MySQL的rpm安装教程
    MySQL基础理论
    Linux shell awk数组使用
    Linux shell awk逻辑控制语句
    Linux shell awk模式使用
    MySQL 查看执行计划
    MySQL 自定义函数
    MySQL 内置函数
  • 原文地址:https://www.cnblogs.com/wangyiming/p/14700327.html
Copyright © 2011-2022 走看看