zoukankan      html  css  js  c++  java
  • 力扣算法题—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 };
  • 相关阅读:
    3.4
    3.3 TensorFlow运行模型 ------- 会话
    3.2 TensorFlow数据模型 ---- 张量
    3.1 TensorFlow计算模型 --- 计算图
    寻找两个有序数组的中位数
    最长子串
    vector的遍历删除
    超时空大决战
    面经七
    面经五
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11774687.html
Copyright © 2011-2022 走看看