-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (86 loc) · 1.53 KB
/
main.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
package main
import "fmt"
type Node struct {
Val int
Next *Node
Previous *Node
}
func (n *Node) AddNode(val int) int {
var rev func(t *Node, val int) int
rev = func(t *Node, val int) int {
if t == nil {
t = &Node{Val: val}
return 0
}
if val == t.Val {
fmt.Println("Node already exists: ", val)
return -1
}
if t.Next == nil {
tmp := t
t.Next = &Node{Val: val, Previous: tmp}
return -2
}
return rev(t.Next, val)
}
return rev(n, val)
}
func (n *Node) Traverse() {
if n == nil {
fmt.Println("-> Empty list!")
}
for t := n; t != nil; t = t.Next {
fmt.Printf("%d ->", t.Val)
}
fmt.Println()
}
func (n *Node) Reverse() {
if n == nil {
fmt.Println("-> Empty list!")
}
tmp := n
for ; tmp.Next != nil; tmp = tmp.Next {
}
for ; tmp.Previous != nil; tmp = tmp.Previous {
fmt.Printf("%d ->", tmp.Val)
}
fmt.Printf("%d ->\n", tmp.Val)
}
func (n *Node) LookupNode(val int) bool {
var rev func(t *Node, val int) bool
rev = func(t *Node, val int) bool {
if t == nil {
return false
}
if val == t.Val {
return true
}
if t.Next == nil {
return false
}
return rev(t.Next, val)
}
return rev(n, val)
}
func (n *Node) Size() (len int) {
for t := n; t != nil; t = t.Next {
len++
}
return
}
func main() {
n := new(Node)
n.AddNode(10)
n.AddNode(5)
n.AddNode(45)
// Node already exists: 5
n.AddNode(5)
// Node already exists: 5
n.AddNode(5)
// 0 ->10 ->5 ->45 ->
n.Traverse()
//Size: 4
fmt.Println("Size:", n.Size())
// 45 ->5 ->10 ->0 ->
n.Reverse()
}