Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→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 };