力扣算法题—143ReorderList

北城余情 提交于 2019-12-03 02:51:35

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 };

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!