File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "bytes"
6
+ )
7
+
8
+ type ListNode struct {
9
+ Val int
10
+ Next * ListNode
11
+ }
12
+
13
+ func (head * ListNode ) String () string {
14
+ var buf = bytes.Buffer {}
15
+ for n := head ; n != nil ; n = n .Next {
16
+ if n != head {
17
+ buf .WriteString (" -> " )
18
+ }
19
+ buf .WriteString (fmt .Sprintf ("[%d]" , n .Val ))
20
+ }
21
+
22
+ return buf .String ()
23
+ }
24
+
25
+ func partition (head * ListNode , x int ) * ListNode {
26
+ if head == nil || head .Next == nil {
27
+ return head
28
+ }
29
+ var newHead , newTail , oldHead , oldTail * ListNode
30
+ for cur := head ; cur != nil ; cur = cur .Next {
31
+ if cur .Val >= x {
32
+ if oldHead == nil {
33
+ oldHead = cur
34
+ }
35
+ oldTail = cur
36
+ } else {
37
+ if newHead == nil {
38
+ newHead , newTail = cur , cur
39
+ } else {
40
+ newTail .Next = cur
41
+ newTail = cur
42
+ }
43
+ if oldTail != nil {
44
+ oldTail .Next = cur .Next
45
+ }
46
+ }
47
+ }
48
+ if newHead == nil {
49
+ return head
50
+ }
51
+ newTail .Next = oldHead
52
+ return newHead
53
+ }
54
+
55
+ func main () {
56
+ h := & ListNode {1 , & ListNode {1 , nil }}
57
+ fmt .Println (h )
58
+ fmt .Println (partition (h , 2 ))
59
+ }
You can’t perform that action at this time.
0 commit comments