題目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
解題思路:
1,先利用快慢指標找到連結串列中間節點
2,將連結串列後半部分進行反轉
3,將連結串列前半部分與反轉後的後半部分進行合併
實現程式碼:
#include <iostream> using namespace std; /* Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example, Given {1,2,3,4}, reorder it to {1,4,2,3}. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; void addNode(ListNode* &head, int val) { ListNode *node = new ListNode(val); if(head == NULL) { head = node; } else { node->next = head; head = node; } } void printList(ListNode *head) { while(head) { cout<<head->val<<" "; head = head->next; } } class Solution { public: void reorderList(ListNode *head) { if(head == NULL || head->next == NULL) return ; ListNode *quick = head; ListNode *slow = head; while(quick->next &&quick->next->next)//採用快慢指標查詢連結串列中間節點,快指標走兩步,慢指標走一步 { quick = quick->next->next; slow = slow->next; } quick = slow; slow = slow->next; quick->next = NULL; reverseList(slow);//將後半部分進行反轉 quick = head; while(quick && slow)//將前半部分與反轉後的後半部分進行合併 { ListNode *t = slow->next; slow->next = quick->next; quick->next = slow; slow = t; quick = quick->next->next; } } void reverseList(ListNode* &head)//採用頭插法進行連結串列反轉 { if(head == NULL || head->next == NULL) return ; ListNode *p = head->next; head->next = NULL; while(p) { ListNode *t = p->next; p->next = head; head = p; p = t; } } }; int main(void) { ListNode *head = new ListNode(6); addNode(head, 5); addNode(head, 4); addNode(head, 3); addNode(head, 2); addNode(head, 1); addNode(head, 0); printList(head); cout<<endl; Solution solution; solution.reorderList(head); printList(head); return 0; }