-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_ll.rb
More file actions
66 lines (55 loc) · 1.14 KB
/
recursive_ll.rb
File metadata and controls
66 lines (55 loc) · 1.14 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
class Recursive_Linked_list
attr_reader :node
attr_accessor :head, :node_counter
def initialize
@head = Node.new(nil)
end
def append(node, current = head)
if current.ref == nil
current.ref = node
elsif current.ref.ref
append(node, current.ref.ref)
else
current.ref.ref = node
end
end
def access_tail(current = head)
if current.ref == nil
return current
elsif current.ref
access_tail(current.ref)
end
end
def pop(current = head)
if current.ref == nil
elsif current.ref.ref == nil
pop_node = current.ref
current.ref = nil
return pop_node
else
pop(current.ref)
end
end
def access_by_position(position, current = head, node_counter = 0)
if node_counter != position
node_counter += 1
access_by_position(position, current.ref, node_counter)
else
current
end
end
def count(current = head)
if current.ref == nil
0
else
1 + count(current.ref)
end
end
end
class Node
attr_accessor :ref, :data # => nil
def initialize(data, ref=nil)
@data = data
@ref = ref
end
end