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

reorder-list

时间:2016-07-17 09:54:34      阅读:139      评论: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             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 };

 

reorder-list

标签:

原文地址:http://www.cnblogs.com/hhboboy/p/5677413.html

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