-
Notifications
You must be signed in to change notification settings - Fork 1
/
linked-list-example.go
94 lines (83 loc) · 1.47 KB
/
linked-list-example.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
package main
import "fmt"
type Node struct {
item int
next *Node
start *Node
}
var (
current *Node
isFirst = true
)
func main() {
node := &Node{}
node.addItem(10)
node.addItem(20)
node.addItem(30)
node.addItem(40)
if node.insertItem(30, 50) {
fmt.Println("Item inserted successfully")
} else {
fmt.Println("Middle item not found insertion failed")
}
node.deleteItem(40)
node.display()
}
func (n *Node) addItem(item int){
if isFirst {
n.item = item
n.next = nil
n.start = n
current = n.start
isFirst = false
} else {
current.next = &Node {
item: item,
next: nil,
}
current = current.next
}
}
func (n *Node) deleteItem(item int) (isFound bool) {
for i, current := 1, n.start; ; i, current = i + 1, current.next {
if i == 1 && item == current.item {
n.start = n.start.next
return true
}
if current.next.item == item {
// delete last node
if current.next.next == nil {
current.next = nil
return true
} else {
current.next = current.next.next
return true
}
}
}
return isFound
}
func (n *Node) insertItem(after int, item int) (isFound bool){
for begin := n.start; ; begin = begin.next {
if begin.item == after {
isFound = true
begin.next = &Node {
item: item,
next: begin.next,
}
return true
}
if begin.next == nil {
break
}
}
return
}
func (n *Node) display() {
for begin := n.start; ; begin = begin.next {
fmt.Println(begin.item)
if begin.next == nil {
break
}
}
}