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