Skip to content

Instantly share code, notes, and snippets.

@astronomy88
Last active August 11, 2016 05:47
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 astronomy88/2f33f0a976d091f51d7f4e8abe390e09 to your computer and use it in GitHub Desktop.
Save astronomy88/2f33f0a976d091f51d7f4e8abe390e09 to your computer and use it in GitHub Desktop.
Queue implementation with linked lists
require './node'
class QueueLinkedList
attr_reader :length
def initialize(item)
@q = Node.new item
@q.next = nil
@current = @q
#-- @current holds the item last queued, to keep track of the end of the queue
#-- assign @current to the initial node
@length = 1
end
def enqueue item
if @q.nil?
initialize item
else
#-- Grab the last node from previous time
@last = @current
@length += 1
#-- Create the new node
temp = Node.new(item)
#-- Point the old node to the new node
@last.next = temp
#-- Save the current node for next time - reassigning @current now
@current = temp
end
end
def dequeue
if @length == 0
return nil
end
@length -= 1
#-- We are attempting to peel off from the first
first = @q.item
@q = @q.next
first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment