-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.go
63 lines (55 loc) · 879 Bytes
/
test.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
// add("A", 0)
// add("B", 1)
// add("D", 2)
// add("C", 2)
// add("Z", 0)
// Z, A, B, C, D
package main
import (
"errors"
"fmt"
)
type (
List struct {
Head *ListNode
Len int
}
ListNode struct {
Next *ListNode
Prev *ListNode
Val string
}
)
func (list *List) add(val string, place int) error {
if place > list.Len {
return errors.New("Can't insert to the current place")
}
list.Len++
cur := list.Head
if cur == nil {
list.Head = &ListNode{nil, nil, val}
return nil
}
for ; place > 1; place-- {
cur = cur.Next
}
next := cur.Next
cur.Next = &ListNode{next, cur, val}
return nil
}
func printList(list *List) {
cur := list.Head
for cur != nil {
fmt.Printf("%s ", cur.Val)
}
fmt.Println()
}
func main() {
list := &List{}
list.add("A", 0)
list.add("B", 1)
list.add("D", 2)
list.add("C", 2)
list.add("Z", 0)
printList(list)
}