-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlinked_list.go
More file actions
119 lines (92 loc) · 2.36 KB
/
linked_list.go
File metadata and controls
119 lines (92 loc) · 2.36 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
//main package has examples shown
// in Hands-On Data Structures and algorithms with Go book
package main
// importing fmt package
import (
"fmt"
)
//Node class
type Node struct {
property int
nextNode *Node
}
// LinkedList class
type LinkedList struct {
headNode *Node
}
//AddToHead method of LinkedList class, AddToHead method adds the node to the start of the linked list.
func (linkedList *LinkedList) AddToHead(property int) {
var node = &Node{}
node.property = property
node.nextNode = nil
if linkedList.headNode != nil {
//fmt.Println(node.property)
node.nextNode = linkedList.headNode
}
linkedList.headNode = node
}
//NodeWithValue method returns Node given parameter property
func (linkedList *LinkedList) NodeWithValue(property int) *Node {
var node *Node
var nodeWith *Node
for node = linkedList.headNode; node != nil; node = node.nextNode {
if node.property == property {
nodeWith = node
break
}
}
return nodeWith
}
//AddAfter method adds a node with nodeProperty after node with property
func (linkedList *LinkedList) AddAfter(nodeProperty int, property int) {
var node = &Node{}
node.property = property
node.nextNode = nil
var nodeWith *Node
nodeWith = linkedList.NodeWithValue(nodeProperty)
if nodeWith != nil {
//fmt.Println(node.property)
node.nextNode = nodeWith.nextNode
nodeWith.nextNode = node
}
}
//LastNode method returns the last Node
func (linkedList *LinkedList) LastNode() *Node {
var node *Node
var lastNode *Node
for node = linkedList.headNode; node != nil; node = node.nextNode {
if node.nextNode == nil {
lastNode = node
}
}
return lastNode
}
//AddToEnd method adds the node with property to the end
func (linkedList *LinkedList) AddToEnd(property int) {
var node = &Node{}
node.property = property
node.nextNode = nil
var lastNode *Node
lastNode = linkedList.LastNode()
if lastNode != nil {
lastNode.nextNode = node
}
}
//IterateList method iterates over LinkedList
func (linkedList *LinkedList) IterateList() {
var node *Node
for node = linkedList.headNode; node != nil; node = node.nextNode {
fmt.Println(node.property)
}
}
// main method
func main() {
var linkedList LinkedList
linkedList = LinkedList{}
linkedList.AddToHead(1)
linkedList.AddToHead(3)
linkedList.AddToEnd(5)
linkedList.AddAfter(1, 7)
//fmt.Println(linkedList.headNode.property)
linkedList.IterateList()
}