-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlinked_list.go
108 lines (86 loc) · 1.55 KB
/
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
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
package main
import (
"fmt"
)
type Node struct {
next *Node
key int
}
type LinkedList struct {
head *Node
}
func (linkedList *LinkedList) push(value int) {
newNode := &Node{
key: value,
}
newNode.next = linkedList.head
linkedList.head = newNode
}
func (linkedList *LinkedList) insertAfter(prevNode *Node, value int) {
if prevNode == nil {
return
}
newNode := &Node{
key: value,
}
newNode.next = prevNode.next
prevNode.next = newNode
}
func (linkedList *LinkedList) append(value int) {
newNode := &Node{
key: value,
}
if linkedList.head == nil {
linkedList.head = newNode
return
}
last := linkedList.head
for last.next != nil {
last = last.next
}
last.next = newNode
}
func (linkedList *LinkedList) print() {
curr := linkedList.head
for curr != nil {
fmt.Println(curr.key)
curr = curr.next
}
}
func (linkedList *LinkedList) delete(value int) {
curr := linkedList.head
if curr != nil && curr.key == value {
linkedList.head = curr.next
return
}
prev := &Node{}
for curr != nil {
if curr.key == value {
prev.next = curr.next
return
}
prev = curr
curr = curr.next
}
}
func main() {
linkedList := LinkedList{}
linkedList.append(6)
linkedList.print()
fmt.Println("-")
linkedList.push(7)
linkedList.print()
fmt.Println("-")
linkedList.push(1)
linkedList.print()
fmt.Println("-")
linkedList.append(8)
linkedList.print()
fmt.Println("-")
linkedList.insertAfter(linkedList.head.next.next, 2)
linkedList.print()
fmt.Println("-")
linkedList.delete(1)
linkedList.print()
fmt.Println("-")
}