-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_linked_list.lua
135 lines (108 loc) · 2.42 KB
/
single_linked_list.lua
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
126
127
128
129
130
131
132
133
134
135
local SingleLinkedList = {}
SingleLinkedList.__index = SingleLinkedList
local function create_node(self, prev_node, el)
local n = {
next = nil,
el = el,
}
if prev_node then
prev_node.next = n
else
n.next = self.first
self.first = n
end
end
local function _find(self, indx)
local prev = nil
local cur = self.first
if not cur or (indx and indx < 1) then
return nil, nil
end
local cur_indx = 1
local found = false
while cur.next do
if indx and indx == cur_indx then
found = true
break
end
prev = cur
cur = cur.next
cur_indx = cur_indx + 1
end
if indx and indx > cur_indx then
return nil, nil
end
return cur, prev
end
function SingleLinkedList:new()
local t = {
first = nil,
}
setmetatable(t, SingleLinkedList)
return t
end
function SingleLinkedList:from(ar)
local l = SingleLinkedList:new()
for _, v in ipairs(ar) do
l:add(v)
end
return l
end
function SingleLinkedList:add(el, indx)
local last_node = _find(self, indx)
create_node(self, last_node, el)
end
function SingleLinkedList:find(indx)
local node = _find(self, indx)
return node and node.el
end
function SingleLinkedList:delete(indx)
local node, prev_node = _find(self, indx)
if not node then
return false
end
local next_node = node.next
if not prev_node then
self.first.next = nil
self.first = next_node
else
prev_node.next = next_node
end
-- for gc
node.next = nil
return true
end
function SingleLinkedList:foreach(fun)
local cur = self.first
if not cur then
return nil
end
while cur do
fun(cur.el)
cur = cur.next
end
return cur
end
function SingleLinkedList:reverse()
local prev = nil
local cur = self.first
if not cur then
return nil
end
local nxt = cur and cur.next
while nxt do
cur.next = prev
prev = cur
cur = nxt
nxt = cur.next
end
cur.next = prev
self.first = cur
end
function SingleLinkedList:to_seq()
local tmp = {}
local sup = function(el) table.insert(tmp, el) end
self:foreach(sup)
return tmp
end
return SingleLinkedList