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

[LeetCode] Reorder List

时间:2014-11-04 14:34:54      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   for   sp   div   

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}.

思路:找到中间节点,将链表的后半部分就地逆置。然后插入到前半部分。

   时间复杂度O(n),空间复杂度O(1) 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         if (head == NULL || head->next == NULL || head->next->next == NULL) 
13             return;
14         
15         int length = 0;
16         for (ListNode *pter = head; pter != NULL; pter = pter->next) {
17             ++length;
18         }
19         
20         int half_length = 1;
21         ListNode *half = head;
22         while (half_length < (length / 2)) {
23             ++half_length;
24             half = half->next;
25         }
26         
27        //reverse
28        ListNode *pter = half->next;
29        half->next = NULL;
30        while (pter != NULL) {
31            ListNode *next_node = pter->next;
32            pter->next = half->next;
33            half->next = pter;
34            pter = next_node;
35        }
36       
37 ListNode *pter2 = head; 38 pter = half->next; 39 while (pter2 != half) { 40 ListNode *next_node = pter->next; 41 half->next =next_node; 42 pter->next = pter2->next; 43 pter2->next = pter; 44 pter2 = pter2->next->next; 45 pter = next_node; 46 } 47 } 48 };

 

[LeetCode] Reorder List

标签:des   style   blog   io   color   ar   for   sp   div   

原文地址:http://www.cnblogs.com/vincently/p/4073442.html

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