-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinkedlist.go
57 lines (45 loc) · 945 Bytes
/
linkedlist.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
package linkedlist
// Node of linkedlist
type Node struct {
data interface{}
next *Node
}
// LinkedList data structure
type LinkedList struct {
head *Node
tail *Node
}
// Insert data to back of linkedlist
// O(1) time complexity
func (list *LinkedList) Insert(data interface{}) {
if list.head == nil {
list.head = &Node{data: data}
list.tail = list.head
return
}
list.tail.next = &Node{data: data}
list.tail = list.tail.next
}
// Delete from linkedlist
// O(n) time complexity
func (list *LinkedList) Delete(data interface{}) {
list.head = deleteHelper(list.head, data)
list.updateTail()
}
func deleteHelper(node *Node, data interface{}) *Node {
if node == nil {
return nil
}
if node.data == data {
return node.next
}
node.next = deleteHelper(node.next, data)
return node
}
func (list *LinkedList) updateTail() {
tmp := list.head
for tmp != nil && tmp.next != nil {
tmp = tmp.next
}
list.tail = tmp
}