-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143.cpp
More file actions
97 lines (89 loc) · 2.46 KB
/
143.cpp
File metadata and controls
97 lines (89 loc) · 2.46 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// 143.cpp
// LeetCode
//
// Created by 张佐玮 on 15/5/20.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Reorder List
//
#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 || head -> next == NULL) {
return;
}
ListNode *walker = head, *runner = head;
while (runner != NULL) {
walker = walker -> next;
runner = runner -> next;
if (runner != NULL) {
runner = runner -> next;
}
}
ListNode *pre = walker, *current = walker -> next;
while (current != NULL) {
ListNode *post = current -> next;
current -> next = pre;
pre = current;
current = post;
}
walker -> next = NULL;
ListNode *first = head, *second = pre, *result = first;
while (first != pre && second != NULL) {
first = first -> next;
result -> next = second;
result = result -> next;
if (first != pre && second != NULL) {
second = second -> next;
result -> next = first;
result = result -> next;
}
}
if (result != NULL) {
result -> next = NULL;
}
}
};
class Test {
private:
static ListNode *arrayToList(int input[], int length) {
if(length < 1)
return NULL;
ListNode *head = new ListNode(input[0]), *tail = head;
for(int i = 1; i < length; i++) {
ListNode *current = new ListNode(input[i]);
tail -> next = current;
tail = tail -> next;
}
return head;
}
static void printListNode(ListNode *head) {
while(head != NULL) {
cout << head -> val << "->";
head = head -> next;
}
cout << "NULL" <<endl;
}
static void runTest(int input[], int length) {
ListNode *head = arrayToList(input, length);
printListNode(head);
Solution solution;
solution.reorderList(head);
printListNode(head);
}
public:
void sample() {
int input1[] = {1, 2, 3}, length1 = 3;
int input2[] = {1, 2, 3, 4}, length2 = 4;
runTest(input1, length1);
runTest(input2, length2);
}
};