Skip to content

Instantly share code, notes, and snippets.

@flada-auxv
Forked from JoshCheek/stack.rb
Created December 4, 2012 03:15
Show Gist options
  • Select an option

  • Save flada-auxv/4200213 to your computer and use it in GitHub Desktop.

Select an option

Save flada-auxv/4200213 to your computer and use it in GitHub Desktop.

Revisions

  1. @JoshCheek JoshCheek created this gist Jul 23, 2011.
    35 changes: 35 additions & 0 deletions stack.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    # The stack I wrote for http://vimeo.com/26391171
    # Note that there is an intentional bug in the each method :)

    class Stack

    Node = Struct.new :data, :next

    def push(data)
    @head = Node.new data, @head
    end

    def pop
    return unless @head
    data = @head.data
    @head = @head.next
    data
    end

    ##
    # Iterates across the stack
    #
    # stack = Stack.new
    # stack.push 5
    # stack.push "abc"
    # array = []
    # stack.each { |element| array << element }
    # array # => ["abc", 5]
    def each
    crnt = @head
    loop do
    yield crnt.data
    crnt = crnt.next
    end
    end
    end