Skip to content

Instantly share code, notes, and snippets.

@gkop
Created February 4, 2015 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkop/e462572280138219bdb6 to your computer and use it in GitHub Desktop.
Save gkop/e462572280138219bdb6 to your computer and use it in GitHub Desktop.
class Node
attr_accessor :value, :next_node, :previous_node
def initialize(value, next_node, previous_node)
@value = value
@next_node = next_node
@previous_node = previous_node
end
end
class DoublyLinkedList
def initialize
# maybe later?
end
def empty?
@head == nil
end
def shift
node_to_return = @head
if node_to_return
@head = @head.next_node
@head.previous_node = nil
if @tail.previous_node == node_to_return
@tail.previous_node = nil
end
node_to_return.value
else
raise "You can't shift an empty list"
# (returning nil would also be
# acceptable here)
end
end
def append(value)
if empty?
# our list is empty
# that means @head and @tail are nil
@head = @tail = Node.new(value, nil, nil)
else
new_node = Node.new(value, nil, @tail)
@tail.next_node = new_node
@tail = new_node
end
self
end
def prepend(value)
if empty?
# our list is empty
# that means @head is nil
@head = @tail = Node.new(value, nil, nil)
else
new_node = Node.new(value, @head, nil)
@head.previous_node = new_node
@head = new_node
end
self
end
def to_s
cursor = @head
while cursor !=nil
print "#{cursor.value}<->"
cursor = cursor.next_node
end
print "\n"
end
end
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment