Class Containers::Stack

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

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. <<
  2. each
  3. empty?
  4. next
  5. pop
  6. push
  7. size

Included modules

  1. Enumerable

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
16:   def initialize(ary=[])
17:     @container = Containers::Deque.new(ary)
18:   end

Public instance methods

<< (obj)

Alias for push

each (&block)

Iterate over the Stack in LIFO order.

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

Returns true if the stack is empty, false otherwise.

[show source]
    # File lib/containers/stack.rb, line 58
58:   def empty?
59:     @container.empty?
60:   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
25:   def next
26:     @container.back
27:   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
45:   def pop
46:     @container.pop_back
47:   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
35:   def push(obj)
36:     @container.push_back(obj)
37:   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
53:   def size
54:     @container.size
55:   end