forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path86. Partition List.go
116 lines (107 loc) · 2.31 KB
/
86. 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
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
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
type ListNode = structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// 解法一 单链表
func partition(head *ListNode, x int) *ListNode {
beforeHead := &ListNode{Val: 0, Next: nil}
before := beforeHead
afterHead := &ListNode{Val: 0, Next: nil}
after := afterHead
for head != nil {
if head.Val < x {
before.Next = head
before = before.Next
} else {
after.Next = head
after = after.Next
}
head = head.Next
}
after.Next = nil
before.Next = afterHead.Next
return beforeHead.Next
}
// DoublyListNode define
type DoublyListNode struct {
Val int
Prev *DoublyListNode
Next *DoublyListNode
}
// 解法二 双链表
func partition1(head *ListNode, x int) *ListNode {
if head == nil || head.Next == nil {
return head
}
DLNHead := genDoublyListNode(head)
cur := DLNHead
for cur != nil {
if cur.Val < x {
tmp := &DoublyListNode{Val: cur.Val, Prev: nil, Next: nil}
compareNode := cur
for compareNode.Prev != nil {
if compareNode.Val >= x && compareNode.Prev.Val < x {
break
}
compareNode = compareNode.Prev
}
if compareNode == DLNHead {
if compareNode.Val < x {
cur = cur.Next
continue
} else {
tmp.Next = DLNHead
DLNHead.Prev = tmp
DLNHead = tmp
}
} else {
tmp.Next = compareNode
tmp.Prev = compareNode.Prev
compareNode.Prev.Next = tmp
compareNode.Prev = tmp
}
deleteNode := cur
if cur.Prev != nil {
deleteNode.Prev.Next = deleteNode.Next
}
if cur.Next != nil {
deleteNode.Next.Prev = deleteNode.Prev
}
}
cur = cur.Next
}
return genListNode(DLNHead)
}
func genDoublyListNode(head *ListNode) *DoublyListNode {
cur := head.Next
DLNHead := &DoublyListNode{Val: head.Val, Prev: nil, Next: nil}
curDLN := DLNHead
for cur != nil {
tmp := &DoublyListNode{Val: cur.Val, Prev: curDLN, Next: nil}
curDLN.Next = tmp
curDLN = tmp
cur = cur.Next
}
return DLNHead
}
func genListNode(head *DoublyListNode) *ListNode {
cur := head.Next
LNHead := &ListNode{Val: head.Val, Next: nil}
curLN := LNHead
for cur != nil {
tmp := &ListNode{Val: cur.Val, Next: nil}
curLN.Next = tmp
curLN = tmp
cur = cur.Next
}
return LNHead
}