题目如下:
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}.
分析如下:
写几个例子,发现可以这么来实现题目要求的转换。首先,把链表分成前半部分和后半部分,然后把后半部分反序,最后把后半部分依次插入前半部分。
我的代码:
//280ms过大集合 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode *head) { if(head==NULL||head->next==NULL||head->next->next==NULL) return; //find the first half( may be either odd or even numbers) int n=0; ListNode* p=head; while(p!=NULL){ n=n+1; p=p->next; } int half_point=n/2+n%2; p=head; n=1; while(n!=half_point){ p=p->next; n++; } //reverse the second half ListNode* second_half_old_start=p->next; p->next=NULL;//bug1 断开list要在断点出赋NULL p=second_half_old_start; ListNode* q=second_half_old_start->next; ListNode* r=q; while(q!=NULL){ r=q->next; q->next=p; p=q; q=r; } second_half_old_start->next=NULL; // insert the second half into the first half. q=head; while(p!=NULL){ r=p->next; //bug2 用r保持当前的链表,否则丢链 p->next=q->next; q->next=p; p=r; q=q->next->next; } return; } };
(1) 非IDE环境下手写,还是有若干bug,哎。
update: 2015-01-05 思路和上面是一样的。
/* *找到2分点。左边一半保留,右边一半反转,新的右边链表逐个加入到左边链表中。 */ //63ms class Solution { public: void reorderList(ListNode *head) { if (head == NULL || head->next == NULL || head->next->next == NULL ) return; //should be at least 3 nodes ListNode* slow = head; ListNode* fast = head; ListNode* first_half_head = head; ListNode* first_half_tail = NULL; ListNode* second_half_head = NULL; while (fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; } first_half_tail = slow; second_half_head = slow->next; first_half_tail->next = NULL; ListNode* p = second_half_head; ListNode* q = second_half_head->next; ListNode* r = NULL; while (q != NULL) { r = q->next; q->next = p; p = q; q = r; } second_half_head->next = NULL; // new tail second_half_head = p; //new head; ListNode* t = head; ListNode* m = second_half_head; while(second_half_head != NULL) { m = m->next; second_half_head->next = head->next; head->next = second_half_head; head = head->next->next; second_half_head = m; } head = first_half_head; } };