Skip to content

Commit 69919f1

Browse files
committed
reorder_list
1 parent db5c848 commit 69919f1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
126126
#### [140. word break II](https://github.com/hitzzc/go-leetcode/tree/master/word_break_II)
127127
#### [141. Linked List Cycle](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle)
128128
#### [142. Linked List Cycle II](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle_II)
129+
#### [143. reorder list](https://github.com/hitzzc/go-leetcode/tree/master/reorder_list)
129130

130131

131132

reorder_list/reorder_list.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package reorder_list
2+
3+
type ListNode struct {
4+
Val int
5+
Next *ListNode
6+
}
7+
8+
func reorderList(head *ListNode) {
9+
slow, fast := head, head
10+
var tail *ListNode
11+
for fast != nil && fast.Next != nil {
12+
tail = slow
13+
slow = slow.Next
14+
fast = fast.Next.Next
15+
}
16+
if tail != nil {
17+
tail.Next = nil
18+
}
19+
var secondHead *ListNode
20+
fast = slow
21+
for fast != nil {
22+
slow = fast
23+
fast = fast.Next
24+
slow.Next = secondHead
25+
secondHead = slow
26+
}
27+
firstHead := head
28+
var p1, p2 *ListNode
29+
for firstHead != nil && secondHead != nil {
30+
p1 = firstHead.Next
31+
p2 = secondHead.Next
32+
firstHead.Next = secondHead
33+
secondHead.Next = p1
34+
if p1 == nil {
35+
secondHead.Next = p2
36+
break
37+
}
38+
firstHead = p1
39+
secondHead = p2
40+
}
41+
return
42+
}

0 commit comments

Comments
 (0)