-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.rb
96 lines (82 loc) · 1.96 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# frozen_string_literal: true
# Linked List based on https://github.com/neilparikh/ruby-linked-list,
# but modified somewhat.
class LinkedList
class Node
attr_accessor :value, :next
def initialize(value, next_node = nil)
@value = value
@next = next_node
end
end # class Node
attr_accessor :first
attr_reader :length
# @param items items with which to initialize the list
def initialize(*items)
@length = items.length
@first = Node.new(items.shift)
items.each { |item| push(item) }
end
# @param value value to add to end of list
# @return self
def push(value)
node = Node.new(value)
current_node = @first
current_node = current_node.next while current_node.next
current_node.next = node
@length += 1
self
end
# Returns the last element from the list and removes it
# @return the last element's value
def pop
case @length
when 0
raise 'List is empty'
when 1
@length = 0
value = @first.value
@first = nil
value
else
current = @first
current = current.next while current.next&.next
value = current.next.value
current.next = nil
@length -= 1
value
end
end
# Adds a value to the beginning of the list
# @param value value to add to beginning of list
# @return self
def unshift(value)
node = Node.new(value, @first)
@first = node
@length += 1
self
end
# Removes the first element from the list
# @return the first element's value
def shift
raise 'List is empty' if @length < 1
return_value = @first.value
@first = @first.next
@length -= 1
return_value
end
# @return the values in this list as an array
def to_a
current_node = @first
array = []
while current_node
array << current_node.value
current_node = current_node.next
end
array
end
# @return the values in this list as an array
def to_ary
to_a
end
end # class LinkedList