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

    思路:

    先找到链表中点,再反转后半部分,再merge两个子链表。

    实现:

     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* middleNode(ListNode* head)
    15     {
    16         if (head == NULL) return NULL;
    17         ListNode* fast = head, *slow = head;
    18         while (fast and fast->next)
    19         {
    20             fast = fast->next->next;
    21             slow = slow->next;
    22         }
    23         return slow;
    24     }
    25     ListNode* reverse(ListNode* head)
    26     {
    27         if (head == NULL or head->next == NULL) return head;
    28         ListNode* pre = head, *cur = head->next;
    29         while (cur)
    30         {
    31             ListNode* nxt = cur->next;
    32             cur->next = pre;
    33             pre = cur;
    34             cur = nxt;
    35         }
    36         head->next = NULL;
    37         return pre;
    38     }
    39     void merge(ListNode* a, ListNode* b)
    40     {
    41         if (b == NULL) return;
    42         while (a)
    43         {
    44             ListNode* x = a->next;
    45             a->next = b;
    46             ListNode* y = b->next;
    47             if (x) b->next = x;
    48             a = x;
    49             b = y;
    50         }
    51     }
    52     void reorderList(ListNode* head)
    53     {
    54         if (head == NULL or head->next == NULL) return;
    55         ListNode* mid = middleNode(head);
    56         ListNode* tmp = head;
    57         while (tmp->next != mid) tmp = tmp->next;
    58         tmp->next = NULL;
    59         auto l = reverse(mid);
    60         merge(head, l);
    61     }
    62 };
  • 相关阅读:
    转载 消灭程序员需要百年吗?(重要参考)
    转载的一篇,代码规范
    自改的删除数据库中所有外键语句
    [转]批量禁用外键后,清空表数据
    我的分组分页查询语句
    Yii 分页方法总结
    25个Apache性能优化技巧推荐
    浅谈MindSpore的动态Shape
    C++开发总结 A
    Linux环境下开发常用命令汇总 A
  • 原文地址:https://www.cnblogs.com/wangyiming/p/15675639.html
Copyright © 2011-2022 走看看