-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00143-reorder_list.go
79 lines (63 loc) · 1.32 KB
/
00143-reorder_list.go
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
// 143: Reorder List
// https://leetcode.com/problems/reorder-list/
package main
import "fmt"
type ListNode struct {
val int
next *ListNode
}
type LinkedList struct {
head *ListNode
}
func llInput(head **ListNode, inputs []int) {
for i:=len(inputs)-1; i>=0; i-- {
node := &ListNode{inputs[i], *head}
*head = node
}
}
func llOutput(head *ListNode) {
for head != nil {
fmt.Print(head.val, " -> ")
head = head.next
}
fmt.Println("NULL")
}
// SOLUTION
func reorderList(head *ListNode) *ListNode {
if head == nil || head.next == nil {return head}
var prev, slow, fast, l1, l2 *ListNode
prev, slow, fast, l1, l2 = nil, head, head, head, nil
for fast!=nil && fast.next!=nil {
prev = slow
slow = slow.next
fast = fast.next.next
}
prev.next = nil
var p, c, n *ListNode
p, c, n = nil, slow, nil
for c!=nil {
n=c.next
c.next=p
p=c
c=n
}
l2 = p
for l1!=nil {
n1, n2 := l1.next, l2.next
l1.next = l2
if n1==nil {break}
l2.next=n1
l1=n1
l2=n2
}
return head
}
func main() {
ll := LinkedList{}
// INPUT
li := []int{1,2,3,4}
llInput(&ll.head, li)
// OUTPUT
result := reorderList(ll.head)
llOutput(result)
}