zoukankan      html  css  js  c++  java
  • leetcode143 重排链表

    思路:

    记录一种递归的方法。

    实现:

     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* work(ListNode* head, int len)
    15     {
    16         if (len == 1) return head;
    17         if (len == 2) return head->next;
    18         ListNode* tail = work(head->next, len - 2);
    19         ListNode* hn = head->next;
    20         ListNode* tmp = tail->next->next; 
    21         head->next = tail->next;
    22         tail->next->next = hn;
    23         tail->next = tmp;
    24         return tail;
    25     }
    26     void reorderList(ListNode* head)
    27     {
    28         if (!head) return;
    29         int len = 0;
    30         ListNode* tmp = head;
    31         while (tmp) { len++; tmp = tmp->next; }
    32         work(head, len);
    33     }
    34 };
  • 相关阅读:
    oracle常用命令(比较常见好用)
    vim编辑器详解
    对话框和打印控件
    winform弹出唯一的窗体
    ListView
    菜单栏和布局
    窗体属性和公共控件
    ASPCMS和WPF
    MVC
    正则表达式
  • 原文地址:https://www.cnblogs.com/wangyiming/p/14688510.html
Copyright © 2011-2022 走看看