-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.go
More file actions
executable file
·125 lines (88 loc) · 1.88 KB
/
linkedList.go
File metadata and controls
executable file
·125 lines (88 loc) · 1.88 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
120
121
122
123
124
125
package main
type SingleListNode struct {
next *SingleListNode
Value interface{}
}
type SingleList struct {
first *SingleListNode
last *SingleListNode
}
func (this *SingleList) Push(val interface{}) {
if this.first == nil {
this.first = &SingleListNode{nil, val}
this.last = this.first
} else {
old := this.first
this.first = &SingleListNode{nil, val}
this.first.next = old
}
}
func (this *SingleList) PushBack(val interface{}) {
if this.first == nil {
this.first = &SingleListNode{nil, val}
this.last = this.first
} else {
this.last.next = &SingleListNode{nil, val}
this.last = this.last.next
}
}
func (this *SingleList) Length() int {
current := this.first
count := 0
for current != nil {
count++
current = current.next
}
return count
}
func (this *SingleList) ToString() string {
current := this.first
out := ""
for current != nil {
out = out + "["+current.Value.(string)+"] "
current = current.next
}
return out
}
func (this *SingleList) Get(index int) interface{} {
counter := 0
for current := this.first; ; current = current.next {
if counter == index {
return current.Value
} else if current.next == nil {
panic("Attempted to get an index greater than list length.")
} else {
counter++
}
}
}
func (this *SingleList) Delete(index int) {
counter := 0
current := this.first
var prev *SingleListNode
for {
if counter == index && prev == nil {
// deleted first elem
this.first = this.first.next
if this.first == nil {
this.last = nil
}
return
} else if counter == index && current.next == nil {
// deleted last elem
prev.next = nil
this.last = prev
return
} else if counter == index {
// deleted any middle elem
prev.next = current.next
return
}
counter++
prev = current
current = current.next
}
}
func NewLinkedList() *SingleList {
return &SingleList{}
}