-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition-list.go
59 lines (53 loc) · 974 Bytes
/
partition-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
package main
import (
"fmt"
"bytes"
)
type ListNode struct {
Val int
Next *ListNode
}
func (head *ListNode) String() string {
var buf = bytes.Buffer{}
for n := head; n != nil; n = n.Next {
if n != head {
buf.WriteString(" -> ")
}
buf.WriteString(fmt.Sprintf("[%d]", n.Val))
}
return buf.String()
}
func partition(head *ListNode, x int) *ListNode {
if head == nil || head.Next == nil {
return head
}
var newHead, newTail, oldHead, oldTail *ListNode
for cur := head; cur != nil; cur = cur.Next {
if cur.Val >= x {
if oldHead == nil {
oldHead = cur
}
oldTail = cur
} else {
if newHead == nil {
newHead, newTail = cur, cur
} else {
newTail.Next = cur
newTail = cur
}
if oldTail != nil {
oldTail.Next = cur.Next
}
}
}
if newHead == nil {
return head
}
newTail.Next = oldHead
return newHead
}
func main() {
h := &ListNode{1, &ListNode{1, nil}}
fmt.Println(h)
fmt.Println(partition(h, 2))
}