Skip to content

Instantly share code, notes, and snippets.

@mtvillwock
Forked from Jberczel/linked_list.rb
Last active August 29, 2015 14:11
Show Gist options
  • Save mtvillwock/1c830b18d9aa11a7c571 to your computer and use it in GitHub Desktop.
Save mtvillwock/1c830b18d9aa11a7c571 to your computer and use it in GitHub Desktop.
Node = Struct.new(:value, :next)
class LinkedList
def initialize(*values)
@head = Node.new(values.shift, nil)
values.each { |v| add(v) }
end
def add(value)
current = @head
while current.next
current = current.next
end
current.next = Node.new(value,nil)
self
end
def delete(value)
current = @head
return @head = @head.next if current.value == value
while current.next
if current.next.value == value
current.next = current.next.next
return @head
end
current = current.next
end
end
def display
current = @head
disp = []
while current
disp << current.value
current = current.next
end
puts disp.join("->")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment