-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.go
74 lines (58 loc) · 1.09 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package datastructures
import (
"errors"
"fmt"
)
type node struct {
data int
next *node
}
// LinkedList is a linked list
type LinkedList struct {
head *node
tail *node
}
var errIndexOutOfRange = errors.New("index out of range")
func (l *LinkedList) Append(data int) {
newNode := node{data: data}
// check if list is empty
// if yes point head and tail to the first element
if l.head == nil {
l.head = &newNode
l.tail = l.head
return
}
// update previous tail to point at new node
// and make new node current tail
l.tail.next = &newNode
l.tail = &newNode
}
func (l *LinkedList) Get(index int) (int, error) {
if l.head == nil {
return 0, errIndexOutOfRange
}
cursor := 0
temp := l.head
for cursor != index {
if temp == nil {
return 0, errIndexOutOfRange
}
temp = temp.next
cursor++
}
return temp.data, nil
}
func (l *LinkedList) String() string {
var s string
if l.head == nil {
return s
}
temp := l.head
s = fmt.Sprintf("%v", temp.data)
temp = temp.next
for temp != nil {
s = fmt.Sprintf("%v, %v", s, temp.data)
temp = temp.next
}
return s
}