Skip to content

Instantly share code, notes, and snippets.

@Jberczel
Created November 12, 2014 18:18
Show Gist options
  • Save Jberczel/02e4cd80a616ab73ec66 to your computer and use it in GitHub Desktop.
Save Jberczel/02e4cd80a616ab73ec66 to your computer and use it in GitHub Desktop.
Single Linked List - ruby implementation for Cracking the Code Interview Questions
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