Class: Algorithms::Containers::Stack

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/containers/stack.rb

Instance Method Summary collapse

Constructor Details

#initialize(ary = []) ⇒ Stack

Create a new stack. Takes an optional array argument to initialize the stack.

s = Algorithms::Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.pop #=> 2


18
19
20
# File 'lib/containers/stack.rb', line 18

def initialize(ary=[])
  @container = Deque.new(ary)
end

Instance Method Details

#each(&block) ⇒ Object

Iterate over the Stack in LIFO order.



65
66
67
# File 'lib/containers/stack.rb', line 65

def each(&block)
  @container.each_backward(&block)
end

#empty?Boolean

Returns true if the stack is empty, false otherwise.

Returns:

  • (Boolean)


60
61
62
# File 'lib/containers/stack.rb', line 60

def empty?
  @container.empty?
end

#nextObject

Returns the next item from the stack but does not remove it.

s = Algorithms::Containers::Stack.new([1, 2, 3])
s.next #=> 3
s.size #=> 3


27
28
29
# File 'lib/containers/stack.rb', line 27

def next
  @container.back
end

#popObject

Removes the next item from the stack and returns it.

s = Algorithms::Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.size #=> 2


47
48
49
# File 'lib/containers/stack.rb', line 47

def pop
  @container.pop_back
end

#push(obj) ⇒ Object Also known as: <<

Adds an item to the stack.

s = Algorithms::Containers::Stack.new([1])
s.push(2)
s.pop #=> 2
s.pop #=> 1


37
38
39
# File 'lib/containers/stack.rb', line 37

def push(obj)
  @container.push_back(obj)
end

#sizeObject

Return the number of items in the stack.

s = Algorithms::Containers::Stack.new([1, 2, 3])
s.size #=> 3


55
56
57
# File 'lib/containers/stack.rb', line 55

def size
  @container.size
end