標籤:leetcode 演算法 面試
【題目】
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}.
【題意】
給定一個鏈表L: L0→L1→…→Ln-1→Ln,對他重新排序成L0→Ln→L1→Ln-1→L2→Ln-2→…
【思路】
將鏈表對半截斷,將後半部分鏈表倒置,然後把前後兩個鏈表錯位合并
本題涉及三個典型的鏈表操作:
1. 找鏈表中點
2. 鏈表倒置
3. 鏈表歸併
【代碼】
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reserve(ListNode *head){ if(head==NULL || head->next==NULL)return head; ListNode* prev=NULL; ListNode* cur=head; ListNode* next=NULL; while(cur){ next=cur->next; cur->next=prev; prev=cur; cur=next; } return prev; } ListNode* findMid(ListNode *head){ if(head==NULL || head->next==NULL)return head; ListNode*prev=NULL; ListNode*p1=head; ListNode*p2=head; while(p2){ prev=p1; p1=p1->next; p2=p2->next; if(p2)p2=p2->next; } prev->next=NULL; return p1; } ListNode* merge(ListNode*head1, ListNode*head2){ ListNode*p1=head1; ListNode*p2=head2; ListNode*head=NULL, *p=NULL; while(p2){ if(head==NULL)head=p1; else p->next=p1; p=p1; p1=p1->next; p->next=p2; p=p2; p2=p2->next; } p->next=p1; return head; } void reorderList(ListNode *head) { if(head==NULL || head->next==NULL)return; ListNode* head2 = findMid(head); head2 = reserve(head2); head=merge(head, head2); }};