File tree Expand file tree Collapse file tree 1 file changed +94
-0
lines changed Expand file tree Collapse file tree 1 file changed +94
-0
lines changed Original file line number Diff line number Diff line change
1
+ local hashset = {}
2
+
3
+ hashset .__index = hashset
4
+
5
+ hashset .Node = {}
6
+ hashset .Node .__index = hashset .Node
7
+
8
+ function hashset .Node .create (key )
9
+ local s = {}
10
+ setmetatable (s , hashset .Node )
11
+
12
+ s .key = key
13
+ s .next = nil
14
+
15
+ return s
16
+ end
17
+
18
+ function hashset .create (hash )
19
+ local s = {}
20
+ setmetatable (s , hashset )
21
+
22
+ if hash == nil then
23
+ hash = function (x ) return x end
24
+ end
25
+
26
+ s .s = {}
27
+ s .N = 0
28
+ s .hash = hash
29
+
30
+ return s
31
+ end
32
+
33
+ function hashset :add (key )
34
+ local h = self .hash (key )
35
+ local x = self .s [h ]
36
+ local found = false
37
+ while x ~= nil do
38
+ if x .key == key then
39
+ found = true
40
+ break
41
+ end
42
+ x = x .next
43
+ end
44
+
45
+ if found == false then
46
+ local old = self .s [h ]
47
+ self .s [h ] = hashset .Node .create (key )
48
+ self .s [h ].next = old
49
+ self .N = self .N + 1
50
+ end
51
+
52
+ end
53
+
54
+ function hashset :contains (key )
55
+ local h = self .hash (key )
56
+ local x = self .s [h ]
57
+ while x ~= nil do
58
+ if x .key == key then
59
+ return true
60
+ end
61
+ x = x .next
62
+ end
63
+ return false
64
+ end
65
+
66
+ function hashset :size ()
67
+ return self .N
68
+ end
69
+
70
+ function hashset :isEmpty ()
71
+ return self .N == 0
72
+ end
73
+
74
+ function hashset :remove (key )
75
+ local h = self .hash (key )
76
+ local x = self .s [h ]
77
+ local prev_x = nil
78
+ while x ~= nil do
79
+ if x .key == key then
80
+ if prev_x == nil then
81
+ self .s [h ] = x .next
82
+ else
83
+ prev_x .next = x .next
84
+ end
85
+ self .N = self .N - 1
86
+ end
87
+ prev_x = x
88
+ x = x .next
89
+ end
90
+
91
+ return nil
92
+ end
93
+
94
+ return hashset
You can’t perform that action at this time.
0 commit comments