[LeetCode]Reorder List
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}
.
思考:[微软原题点击]。O(n2)方法这里就不贴了。因为每次要插入的结点都是尾结点,从头结点开始寻找时间都花费在查询上。题意说只可以改变.next,这算是一个提示吧。我们可以翻转待插入链表结点,这样每次查询尾结点时间为O(1),极大减小时间复杂度。翻转链表,合并链表,非常棒的一道题目。
class Solution { public: ListNode *Reverse(ListNode *head) { if(!head||!head->next) return head; ListNode *p=head; ListNode *q=p->next; while(q) { p->next=q->next; q->next=head; head=q; q=p->next; } return head; } ListNode *Merge(ListNode *head1,ListNode *head2) { ListNode *p=head1; ListNode *q=head2; ListNode *pN,*qN; while(q) { pN=p->next; qN=q->next; p->next=q; q->next=pN; p=pN; q=qN; } return head1; } void reorderList(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(!head||!head->next||!head->next->next) return; ListNode *p; p=head; int num=0; while(p) { p=p->next; num++; } if(num%2) num=num/2; else num=num/2-1; p=head; while(num--) p=p->next; ListNode *head2=p->next; p->next=NULL; head2=Reverse(head2); head=Merge(head,head2); } };