class Containers::Stack

  1. lib/containers/stack.rb
Parent: Containers

A Stack is a container that keeps elements in a last-in first-out (LIFO) order. There are many uses for stacks, including prefix-infix-postfix conversion and backtracking problems.

This implementation uses a doubly-linked list, guaranteeing O(1) complexity for all operations.

Methods

Public Class

  1. new

Public Instance

  1. each
  2. empty?
  3. next
  4. pop
  5. push
  6. size

Included modules

  1. Enumerable

Public Instance Aliases

<< -> push

Public Class methods

new (ary=[])

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

s = Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.pop #=> 2
[show source]
# File lib/containers/stack.rb, line 16
def initialize(ary=[])
  @container = Containers::Deque.new(ary)
end

Public Instance methods

each (&block)

Iterate over the Stack in LIFO order.

[show source]
# File lib/containers/stack.rb, line 63
def each(&block)
  @container.each_backward(&block)
end
empty? ()

Returns true if the stack is empty, false otherwise.

[show source]
# File lib/containers/stack.rb, line 58
def empty?
  @container.empty?
end
next ()

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

s = Containers::Stack.new([1, 2, 3])
s.next #=> 3
s.size #=> 3
[show source]
# File lib/containers/stack.rb, line 25
def next
  @container.back
end
pop ()

Removes the next item from the stack and returns it.

s = Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.size #=> 2
[show source]
# File lib/containers/stack.rb, line 45
def pop
  @container.pop_back
end
push (obj)

Adds an item to the stack.

s = Containers::Stack.new([1])
s.push(2)
s.pop #=> 2
s.pop #=> 1
[show source]
# File lib/containers/stack.rb, line 35
def push(obj)
  @container.push_back(obj)
end
size ()

Return the number of items in the stack.

s = Containers::Stack.new([1, 2, 3])
s.size #=> 3
[show source]
# File lib/containers/stack.rb, line 53
def size
  @container.size
end