leetcode143 Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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  * 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 class Solution {
10 public:
11     void reorderList(ListNode* head) {
12         //分段
13         ListNode *p1,*p2;
14         p1=head;
15         p2=head;
16         if(!p2)
17             return;
18         p2=p2->next;
19         
20         if(!p2)
21             return;
22             
23         while(p1&&p1->next&&p2&&p2->next)
24         {
25             p1=p1->next;
26             p2=p2->next;
27             if(p2)
28                 p2=p2->next;
29         }
30         if(p1)
31         {
32             p2=p1->next;
33             p1->next=NULL;
34         }
35         p1=head;
36         
37         if(p1==p2)
38             return;
39         
40         //反转
41         ListNode *tnode=p2;
42         p2=p2->next;
43         tnode->next=NULL;
44         
45         while(p2)
46         {
47             ListNode *temp=p2;
48             p2=p2->next;
49             temp->next=tnode;
50             tnode=temp;
51         }
52         
53         //连接
54         ListNode *t=tnode;
55         
56         while(p1)
57         {
58             
59             if(t)
60             {
61                 ListNode *p12=p1;
62                 p1=p1->next;
63                 ListNode *t2=t;
64                 t=t->next;
65                 t2->next=p12->next;
66                 p12->next=t2;
67             }
68             else
69                 break;
70         }
71     }
72 };

note:反转时,42要放在43前面;

 

posted @ 2016-05-09 21:41  西小贝  阅读(179)  评论(0编辑  收藏  举报