Skip to content

Instantly share code, notes, and snippets.

@jordanluyke
Last active September 2, 2020 03:03
Show Gist options
  • Save jordanluyke/7f0b0ad40970d7986cdd to your computer and use it in GitHub Desktop.
Save jordanluyke/7f0b0ad40970d7986cdd to your computer and use it in GitHub Desktop.
Linked list example in Ruby
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