代码改变世界

leetcode - Reorder List

2013-11-11 21:55  张汉生  阅读(136)  评论(0编辑  收藏  举报

 

 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         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if (head ==NULL || head->next == NULL){
15             return;
16         }
17         // split the lists to two parts
18         ListNode * lhead=head, *ltail=head, *rhead=head->next; // split the lists to two parts
19         ListNode * itr = head->next;
20         while ((itr!=NULL) && itr->next !=NULL){
21             ltail = ltail->next;
22             rhead = rhead->next;
23             itr = (itr->next)->next;
24         }
25         ltail->next = NULL;
26         //reverse the right part
27         ListNode * last = rhead;
28         itr = rhead->next;
29         while (itr!=NULL){
30             ListNode * tmp = itr->next;
31             itr->next = last;
32             last = itr;
33             itr = tmp;
34         }
35         rhead->next = NULL;
36         rhead = last;
37         //merge the two parts
38         while (lhead!=NULL){
39             ListNode * tmp = lhead->next;
40             if (rhead !=NULL){
41                 ListNode * tmp1 = rhead->next;
42                 lhead->next = rhead;
43                 rhead->next = tmp;
44                 rhead = tmp1;
45             }
46             lhead = tmp;
47         }
48         return;
49     }
50 };