-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion29.go
More file actions
38 lines (29 loc) · 733 Bytes
/
question29.go
File metadata and controls
38 lines (29 loc) · 733 Bytes
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
package chapter04
import "github.com/syhily/code-interviews/common"
func insertNodeIntoCircle(node *common.ListNode, value int) *common.ListNode {
if node == nil {
node = &common.ListNode{Value: value}
node.Next = node
return node
}
start, max := node.Next, node
n := &common.ListNode{Value: value}
for start != node {
if start.Value > max.Value {
max = start
}
if value > start.Value && value < start.Next.Value {
insertAfterNode(start, n)
return node
}
start = start.Next
}
// Couldn't find the right position, insert after the max node.
insertAfterNode(max, n)
return node
}
func insertAfterNode(start, node *common.ListNode) {
next := start.Next
start.Next = node
node.Next = next
}