forked from neilparikh/ruby-linked-list
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.rb
80 lines (72 loc) · 1.57 KB
/
linked_list.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Node
attr_accessor :value, :next
def initialize(value, next_node = nil)
@value = value
@next = next_node
end
end
class List
attr_accessor :first
attr_reader :length
def initialize(*items)
@length = items.length
@first = Node.new(items.shift)
items.each { |item| self.push(item) }
end
# adds value to end of list
# returns self
def push(value)
node = Node.new(value)
current_node = @first
while current_node.next != nil
current_node = current_node.next
end
current_node.next = node
@length += 1
return self
end
# Removes last element from list
# returns that element's value
def pop
raise "List is empty" if @length < 1
current_node = @first
done = false
while !done
if current_node.next.next == nil
done = true
else
current_node = current_node.next
end
end
to_return = current_node.next.value
current_node.next = nil
@length -= 1
return to_return
end
# adds value to beginning of list
# returns self
def unshift(value)
node = Node.new(value, @first)
@first = node
@length += 1
return self
end
# Removes first element from list
# returns that element's value
def shift
raise "List is empty" if @length < 1
to_return = @first.value
@first = @first.next
@length -= 1
return to_return
end
def to_a
current_node = @first
array = []
while current_node != nil
array << current_node.value
current_node = current_node.next
end
return array
end
end