Is there some advantage to filling a stack with nils and interpreting the "top" as the last non-nil value?

Posted by dwilbank on Stack Overflow See other posts from Stack Overflow or by dwilbank
Published on 2013-10-26T15:34:22Z Indexed on 2013/10/26 15:54 UTC
Read the original article Hit count: 343

Filed under:

While working on a rubymonk exercise, I am asked to implement a stack with a hard size limit. It should return 'nil' if I try to push too many values, or if I try to pop an empty stack.

My solution is below, followed by their solution. Mine passes every test I can give it in my IDE, while it fails rubymonk's test. But that isn't my question.

Question is, why did they choose to fill the stack with nils instead of letting it shrink and grow like it does in my version?

It just makes their code more complex.

Here's my solution:

class Stack
  def initialize(size)
    @max = size
    @store = Array.new
  end

  def pop
    empty? ? nil : @store.pop
  end

  def push(element)
    return nil if full?
    @store.push(element)
  end

  def size
    @store.size
  end

  def look
    @store.last
  end

  private

  def full?
    @store.size == @max
  end

  def empty?
    @store.size == 0
  end
end

and here is the accepted answer

class Stack
  def initialize(size)
    @size = size
    @store = Array.new(@size)
    @top = -1
  end

  def pop
    if empty?
      nil
    else
      popped = @store[@top]
      @store[@top] = nil
      @top = @top.pred
      popped
    end
  end

  def push(element)
    if full? or element.nil?
      nil
    else
      @top = @top.succ
      @store[@top] = element
      self
    end
  end

  def size
    @size
  end

  def look
    @store[@top]
  end

  private

  def full?
    @top == (@size - 1)
  end

  def empty?
    @top == -1
  end
end

© Stack Overflow or respective owner

Related posts about ruby