Skip to content

Instantly share code, notes, and snippets.

@burke
Created April 8, 2009 02:16
Show Gist options
  • Save burke/91589 to your computer and use it in GitHub Desktop.
Save burke/91589 to your computer and use it in GitHub Desktop.
class LinkedList
include Enumerable
def initialize(options)
@sorted = options.delete(:sorted) || false
@double = options.delete(:double) || false
@behaviour = options.delete(:behaviour)
@behaviour = :stack unless [:stack, :queue].include?(@behaviour)
@head = nil
@tail = nil
end
def each
curr = @head
begin yield curr.data end until (curr = curr.nxt).nil?
end
def unsorted_add(item)
@head = Node.new(item,@head)
end
def sorted_add(item)
if @head.nil? or (item < @head.data)
@head = Node.new(item, @head)
else
curr = @head
until (curr.nxt.nil? or (item < curr.nxt.data)) do
curr = curr.nxt
end
curr.nxt = Node.new(item, curr.nxt)
end
end
def double_unsorted_add(item)
if @behaviour == :stack
@head = Node.new(item,@head,nil)
@head.nxt.prv = @head if @head.nxt
elsif @behaviour == :queue
@tail = Node.new(item, nil, @tail)
@tail.prv.nxt = @tail if @tail
end
end
def double_sorted_add(item)
raise NotImplementedError, "Double Sorted Linked Lists are not supported"
end
def add(item)
if @double
@sorted ? double_sorted_add(item) : double_unsorted_add(item)
else
@sorted ? sorted_add(item) : unsorted_add(item)
end
end
def pop(side=:front)
if side == :front
value = @head.data
@head = @head.nxt
@head.prv = nil if @head
return value
elsif side == :back
raise TypeError, "Won't remove from tail of a single LL" unless @double
value = @tail.data
@tail = @tail.prv
@tail.nxt = nil if @tail
return value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment