1
+ // 思路一 on的时间复杂度 on的空间复杂度
2
+ // Runtime: 60 ms, faster than 83.33% of C++ online submissions for Reorder List.
3
+ // Memory Usage: 11.1 MB, less than 0.92% of C++ online submissions for Reorder List.
4
+
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * struct ListNode {
8
+ * int val;
9
+ * ListNode *next;
10
+ * ListNode(int x) : val(x), next(NULL) {}
11
+ * };
12
+ */
13
+ class Solution {
14
+ public:
15
+ void reorderList (ListNode* head)
16
+ {
17
+ if (head == 0 || head->next == 0 )
18
+ return ;
19
+
20
+ ListNode *root = head;
21
+
22
+ stack<ListNode*> memo;
23
+ while (head != 0 )
24
+ {
25
+ memo.push (head);
26
+ head = head->next ;
27
+ }
28
+
29
+ for (head = root;;)
30
+ {
31
+ ListNode *tail = memo.top ();
32
+ memo.pop ();
33
+ ListNode *temp = head->next ;
34
+ head->next = tail;
35
+ tail->next = temp;
36
+ head = temp;
37
+
38
+ if (head->next == tail)
39
+ {
40
+ head->next = 0 ;
41
+ break ;
42
+ }
43
+ }
44
+ }
45
+ };
46
+
47
+ // 思路二 on的时间复杂度 o1的空间复杂度
48
+ // Runtime: 56 ms, faster than 100.00% of C++ online submissions for Reorder List.
49
+ // Memory Usage: 10.1 MB, less than 0.92% of C++ online submissions for Reorder List.
50
+
51
+ class Solution
52
+ {
53
+ public:
54
+ void reorderList (ListNode* head)
55
+ {
56
+ if (head == 0 || head->next == 0 || head->next ->next == 0 )
57
+ return ;
58
+
59
+ // 切分链表
60
+ ListNode *slowPtr = head, *fastPtr = head;
61
+ while (fastPtr->next != 0 && fastPtr->next ->next != 0 )
62
+ {
63
+ slowPtr = slowPtr->next ;
64
+ fastPtr = fastPtr->next ->next ;
65
+ }
66
+
67
+ // 逆转后半部分
68
+ ListNode *preNode = slowPtr, *nextNode;
69
+ fastPtr = slowPtr->next ;
70
+ slowPtr->next = 0 ;
71
+ while (fastPtr != 0 )
72
+ {
73
+ nextNode = fastPtr->next ;
74
+ fastPtr->next = preNode;
75
+ preNode = fastPtr;
76
+ fastPtr = nextNode;
77
+ }
78
+ fastPtr = preNode;
79
+
80
+ // 将两个部分链表合并
81
+ slowPtr = head;
82
+ while (slowPtr != fastPtr && slowPtr != 0 )
83
+ {
84
+ ListNode *tempFast = fastPtr;
85
+ ListNode *tempSlow = slowPtr;
86
+
87
+ fastPtr = fastPtr->next ;
88
+ slowPtr = slowPtr->next ;
89
+
90
+ tempFast->next = slowPtr;
91
+ tempSlow->next = tempFast;
92
+ }
93
+ slowPtr = 0 ;
94
+ }
95
+ };
0 commit comments