-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy path143_Reorder_List
More file actions
130 lines (111 loc) · 3.03 KB
/
143_Reorder_List
File metadata and controls
130 lines (111 loc) · 3.03 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
Leetcode 143: Reorder List
Detailed video explanation: https://youtu.be/meOY1wajrnw
=============================================
C++:
----
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(!head || !head->next) return;
ListNode *slow = head, *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode *prev = nullptr, *curr = slow, *tmp;
while(curr){
tmp = curr->next;
curr->next = prev;
prev = curr;
curr = tmp;
}
ListNode *n1 = head, *n2 = prev;
while(n2->next){
tmp = n1->next;
n1->next = n2;
n1 = tmp;
tmp = n2->next;
n2->next = n1;
n2 = tmp;
}
}
};
Java:
-----
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null) return;
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode prev = null, curr = slow, tmp;
while(curr != null){
tmp = curr.next;
curr.next = prev;
prev = curr;
curr = tmp;
}
ListNode n1 = head, n2 = prev;
while(n2.next != null){
tmp = n1.next;
n1.next = n2;
n1 = tmp;
tmp = n2.next;
n2.next = n1;
n2 = tmp;
}
}
}
Python3:
--------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if head == None or head.next == None: return
slow, fast = head, head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
prev, curr = None, slow
while curr != None:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
n1, n2 = head, prev
while n2.next != None:
tmp = n1.next
n1.next = n2
n1 = tmp
tmp = n2.next
n2.next = n1
n2 = tmp