Reorder List

先将链表用快慢指针分成两部分,再将后一半进行倒置,倒置后再合并。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9  
10  ListNode* reverse(ListNode *head)
11 {
12     if(head==NULL||head->next==NULL)return head;
13     ListNode prehead(0),*p;
14     prehead.next=head;
15     while(head->next)
16     {
17         p=head->next;
18         head->next=p->next;
19         p->next=prehead.next;
20         prehead.next=p;
21     }
22     
23     return prehead.next;
24 }
25 
26 class Solution {
27 public:
28     ListNode *reorderList(ListNode* head) {
29       if(head==NULL||head->next==NULL)return head;
30       ListNode prehead(0),*slower,*fast,*start;
31       prehead.next=head;
32       slower=fast=head;
33       while(fast&&fast->next)
34       {
35           slower=slower->next;
36           fast=fast->next->next;
37       }
38       start=slower->next;
39       slower->next=NULL;
40      start=reverse(start);
41      while(head&&start)
42      {
43         fast=start->next;
44         start->next=head->next;
45         head->next=start;
46         
47         head=head->next->next;
48         start=fast;
49      }
50      
51      return prehead.next; 
52       
53         
54     }
55 };

 

posted on 2015-10-20 14:11  RenewDo  阅读(173)  评论(0编辑  收藏  举报

导航