Basic Stack and Queue

Stack

class Stack

  def initialize
    @stack = []
  end

  def push(*element)
    @stack.push(element)
    @stack.flatten!
  end

  def pop
    @stack.pop
    @stack
  end

  def peek
    @stack.last
  end

  def size
    @stack.length
  end
end

s = Stack.new
s.push(1,2,3,4,5) #=>[1, 2, 3, 4, 5]
s.push([6,7,8],[9,[10]]) #=>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s.pop #=>[1, 2, 3, 4, 5, 6, 7, 8, 9]
s.peek #=> 9
s.size #=> 9

Queue

class Queue
  def initialize
    @queue = []
  end

  def enqueue(*elements)
    @queue.unshift(elements)
    @queue.flatten!
  end

  def dequeue
    @queue.pop
    @queue
  end

  def peek
    @queue.last
  end

  def size
    @queue.size
  end
end

q = Queue.new
q.enqueue(1,2,3,4,5) #=>[1, 2, 3, 4, 5]
q.enqueue("hello!") #["hello!", 1, 2, 3, 4, 5]
q.enqueue([6,7,8],[9,[10]]) #=>[6, 7, 8, 9, 10, "hello!", 1, 2, 3, 4, 5]
q.dequeue #=>[6, 7, 8, 9, 10, "hello!", 1, 2, 3, 4]
q.peek #=> 4
q.size #=> 10

Leave a Reply