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