-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlinkedlist.rb
65 lines (56 loc) · 1.03 KB
/
linkedlist.rb
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
class List
attr_accessor :head, :tail
def initialize(*args)
@head = args.pop
@tail = nil
process(args)
end
def insert_first(val)
new_node = List.new(@head)
new_node.tail = @tail
@head = val
@tail = new_node
end
def insert_after(node, new_data, cur_nodes=self)
if(cur_nodes.head == node)
new_node = List.new(new_data)
new_node.tail = cur_nodes.tail
cur_nodes.tail = new_node
else
insert_after(node, new_data, cur_nodes.tail)
end
end
# Find the count
def count
if @tail == nil
count = 1
else
count = 1 + @tail.count
end
end
# Get the last item
def last
if @tail == nil
@head
else
@tail.last
end
end
# Reverse
def reverse(new_list=List.new(@head), cur_list=@tail)
if cur_list == nil
new_list
else
new_list.insert_first(cur_list.head)
reverse(new_list,cur_list.tail)
end
end
private
def process(args)
if !args.empty?
x = args.pop()
insert_first(x)
process(args)
end
end
end