• 力扣算法题—143ReorderList


    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example 1:

    Given 1->2->3->4, reorder it to 1->4->2->3.

    Example 2:

    Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

    Solution:
      使用快慢指针,得到后半部分的链表
      使用栈存储后半部分的链表来替代翻转链表
     1 class Solution {
     2 public:
     3     void reorderList(ListNode* head) {
     4         if (head == nullptr || head->next == nullptr)return;
     5         ListNode* slow = head, *fast = head;
     6         while (fast && fast->next)
     7         {
     8             slow = slow->next;
     9             fast = fast->next->next;
    10         }
    11         fast = slow->next;
    12         slow->next = nullptr;
    13         stack<ListNode*>s;
    14         while (fast)
    15         {
    16             s.push(fast);
    17             fast = fast->next;
    18         }
    19         slow = head;
    20         while (!s.empty())
    21         {
    22             ListNode* p = slow->next;
    23             slow->next = s.top();
    24             s.pop();
    25             slow->next->next = p;
    26             slow = p;
    27         }
    28         return;
    29     }
    30 };
  • 相关阅读:
    extjs数据类型
    Extjs 动态控制列显示
    400
    extjs主单清单同时编辑提交
    js-map模拟
    Leetcode 407.接雨水
    Leetcode 406.根据身高重建队列
    Leetcode 405.数字转化为十六进制数
    Leetcode 402.移掉k位数字
    Leetcode 401.二进制手表
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11774687.html
Copyright © 2020-2023  润新知