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             ListNode *p1, *p2;
13 
14             if (head == NULL || head->next == NULL || head->next->next == NULL)
15                 return;
16 
17             p1 = head;
18             p2=head->next;
19             while (p1 != p2)
20             {
21                 p2 = p1;
22                 while (p2->next->next != NULL)
23                 {
24                     p2 = p2->next;
25                 }
26                 if (p1 != p2)
27                 {
28                     p2->next->next = p1->next;
29                     p1->next = p2->next;
30                     p2->next = NULL;
31                     p1 = p1->next->next;
32                 }
33 
34             }
35     }
36 };

 

posted @ 2016-07-16 22:35  hhboboy  阅读(139)  评论(0编辑  收藏  举报