Created
February 27, 2014 20:02
-
-
Save jordanluyke/9258287 to your computer and use it in GitHub Desktop.
Linked list in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
attr_accessor :value, :next_node | |
def initialize(value, next_node = nil) | |
@value = value | |
@next_node = next_node | |
end | |
end | |
class LinkedList | |
attr_accessor :head | |
def initialize(value) | |
@head = Node.new(value) | |
end | |
def push(value) | |
current_node = @head | |
if @head.value == nil | |
@head = Node.new(value) | |
else | |
while current_node != nil | |
if current_node.next_node == nil | |
current_node.next_node = Node.new(value) | |
break | |
end | |
current_node = current_node.next_node | |
end | |
end | |
end | |
def delete_value(value) | |
current_node = @head | |
if @head.value == value | |
@head = @head.next_node | |
else | |
while current_node != nil | |
if current_node.next_node.value == value | |
current_node.next_node = current_node.next_node.next_node | |
break | |
end | |
current_node = current_node.next_node | |
end | |
end | |
end | |
def pop | |
current_node = @head | |
while current_node != nil | |
if current_node.next_node.next_node == nil | |
current_node.next_node = nil | |
break | |
end | |
current_node = current_node.next_node | |
end | |
end | |
def to_array | |
temp_array = [] | |
current_node = @head | |
while current_node != nil | |
temp_array << current_node.value | |
current_node = current_node.next_node | |
end | |
return temp_array | |
end | |
end | |
def assert_equal(input1, input2) | |
raise "Does not equal" unless input1 == input2 | |
end | |
link_list = LinkedList.new(5) | |
link_list.push(7) | |
link_list.push(9) | |
link_list.push(11) | |
link_list.push(13) | |
assert_equal(link_list.to_array,[5,7,9,11,13]) | |
link_list.pop | |
assert_equal(link_list.to_array,[5,7,9,11]) | |
link_list.delete_value(9) | |
assert_equal(link_list.to_array,[5,7,11]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment