首页 > 其他 > 详细

Leetcode: Reorder List

时间:2014-02-15 07:20:38      阅读:285      评论:0      收藏:0      [点我收藏+]

思路

1. 将后半段截取下来再倒序, 插入到前半段, 时间复杂度为 o(n)

 

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
using namespace std;
 
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };
 
class Solution {
public:
    void reorderList(ListNode *head) {
      if(head == NULL)
        return;
       
        int size = 0;
        ListNode *curNode = head;
        while(curNode) {
            size++;
            curNode = curNode->next;
        }  
 
        int step = size - (size >> 1); // pick the larger part
        ListNode *cursor1 = head, *cursor2 = head;
         
      while(--step)
            cursor2 = cursor2->next;
      ListNode *tmp = cursor2;
       
      if(tmp != NULL) {
        cursor2 = tmp->next;
        tmp->next = NULL;
      }
 
        cursor2 = reverseList(cursor2);
        while(cursor2) {
            ListNode *tmp = cursor2;
            cursor2 = cursor2->next;
            tmp->next = cursor1->next;
            cursor1->next = tmp;
            cursor1 = tmp->next;
        }
    }
 
    ListNode* reverseList(ListNode* head) {
        if(head == NULL)
            return head;
 
        ListNode *curNode = head;
        while(curNode->next) {
            ListNode *nextNode = curNode->next;
            curNode->next = nextNode->next;
            nextNode->next = head;
            head = nextNode;
        }
        return head;
    }
};
 
int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8};
    ListNode* list[10];
    int len = 3;
    for(int i = 0; i < len; i ++)
        list[i] = new ListNode(arr[i]);
    for(int i = 0; i < len-1; i ++)
        list[i]->next = list[i+1];
    (new Solution())->reorderList(list[0]);
    ListNode *lists = list[0];
    while(lists) {
        cout << lists->val << " ";
        lists = lists->next;
    }
    cout << endl;
    return 0;
}

  

Leetcode: Reorder List

原文:http://www.cnblogs.com/xinsheng/p/3550121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!