码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode143 Reorder List

时间:2016-05-09 22:13:38      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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前面;

 

leetcode143 Reorder List

标签:

原文地址:http://www.cnblogs.com/jsir2016bky/p/5475560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!