Repository navigation
Expand file tree
/
Copy path21_linked_list.eps
More file actions
73 lines (66 loc) · 1.47 KB
/
Copy path21_linked_list.eps
File metadata and controls
73 lines (66 loc) · 1.47 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
# 每个节点占两格内存:$node 是值,$(node + 1) 是下一个节点
class List {
function init() {
self.head = null
self.size = 0
}
function push(value) {
var node = memory(2)
$node = value
$(node + 1) = self.head
self.head = node
self.size = self.size + 1
}
function pop() {
if (self.head == null) {
return null
}
var node = self.head
var value = $node
self.head = $(node + 1)
self.size = self.size - 1
return value
}
function at(index) {
if (index < 0 or index >= self.size) {
return null
}
var node = self.head
var current = 0
while (current < index) {
node = $(node + 1)
current = current + 1
}
return $node
}
function length() {
return self.size
}
function toString() {
var text = "["
var node = self.head
var first = true
while (node != null) {
if (not first) {
text = text + ", "
}
text = text + String($node)
first = false
node = $(node + 1)
}
return text + "]"
}
}
var list = List()
list.push(1)
list.push(2)
list.push(3)
output(list)
output(list.length())
output(list.at(1))
output(list.pop())
output(list)
output(list.pop())
output(list.pop())
output(list.pop())
output(list.length())