ruby Ruby的算法和数据结构 - #5 Stack

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby的算法和数据结构 - #5 Stack相关的知识,希望对你有一定的参考价值。

#Ruby doesn't provide an explicit 'stack' but for all practical purposes, the Array provided by Ruby can be treated as a full-fledged stack.

# Based on the ideas from : http://macdevelopertips.com/ruby/using-a-stack-with-ruby.html
# Stacks are a Last In First Out Data Structure

class Stack
    def initialize
        @elements = []
    end
    
    def length
        @elements.length
    end

    # Return self
    def push(x)
        @elements.push x
        self 
    end
    
    def pop
        @elements.pop
    end
    
    def peek
        @elements[-1]   
    end

    def display
        puts "(LeftMost : Oldest Element) " + @elements.join("<-") +" (RightMost : Newest Element)"
    end
end

testStack = Stack.new()
# Display initial (empty stack)
testStack.display
testStack.push(3).push(5).push(10)
# Now display stack
testStack.display
# Check the value at the top of the head
popped = testStack.pop
puts "Popped the value : " + popped.to_s
# Now the stack is ...
testStack.display
popped = testStack.pop
puts "Popped the value : " + popped.to_s
# Now the stack is ...
testStack.display


=begin

Sample Output :
~/work/ruby_tutorials$ ruby stack.rb
(LeftMost : Oldest Element)  (RightMost : Newest Element)
(LeftMost : Oldest Element) 3<-5<-10 (RightMost : Newest Element)
Popped the value : 10
(LeftMost : Oldest Element) 3<-5 (RightMost : Newest Element)
Popped the value : 5
(LeftMost : Oldest Element) 3 (RightMost : Newest Element)
=end

以上是关于ruby Ruby的算法和数据结构 - #5 Stack的主要内容,如果未能解决你的问题,请参考以下文章

ruby Ruby的算法和数据结构 - #8二叉树

ruby Ruby的算法和数据结构 - #7 LinkedList

ruby Ruby的算法和数据结构 - #3快速排序

ruby Ruby的算法和数据结构 - #2选择排序

ruby Ruby的算法和数据结构 - #1插入排序

ruby Ruby的算法和数据结构 - #4 Merge Sort