-
Notifications
You must be signed in to change notification settings - Fork 1
/
double_linked_list.go
81 lines (71 loc) · 1.34 KB
/
double_linked_list.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
package data_structure_go
type nodeDL struct {
Data interface{}
Next *nodeDL
Prev *nodeDL
}
//Make double linked list
type nodeListDL struct {
Head *nodeDL
Tail *nodeDL
length int
}
func (n *nodeListDL) IsEmpty() bool {
return n.Head == nil && n.length == 0
}
func NewDoubleLinkedList() *nodeListDL {
return &nodeListDL{
Head: nil,
Tail: nil,
length: 0,
}
}
func (n *nodeListDL) AddFirst(data interface{}) {
newNode := &nodeDL{Data: data}
if n.Head == nil {
n.Head = newNode
n.Tail = newNode
n.length++
return
}
newNode.Next = n.Head
newNode.Prev = nil
n.Head = newNode
n.length++
}
func (n *nodeListDL) AddLast(data interface{}) {
newNode := &nodeDL{Data: data}
if n.Head == nil && n.Tail == nil {
n.Head = newNode
n.Tail = newNode
n.length++
return
}
n.Tail.Next = newNode
newNode.Prev = n.Tail
n.Tail = newNode
n.length++
}
func (n *nodeListDL) GetDataByIndex(index int) interface{} {
return n.getNodeByIndex(index).Data
}
func (n *nodeListDL) getNodeByIndex(index int) *nodeDL {
temp := n.Head
for i := 0; i < index; i++ {
if i == index-1 {
return temp
}
temp = temp.Next
}
return nil
}
func (n *nodeListDL) DeleteData(index int) bool {
node := n.getNodeByIndex(index)
if node == n.Head {
n.Head = n.Head.Next
n.Head.Prev = nil
n.length--
return !(node == n.Head)
}
return false
}