Class: DSA::Stack

Inherits:
Object
  • Object
show all
Defined in:
lib/dsa-ruby/stack.rb

Overview

DSA::Stack - Last-In-First-Out (LIFO) data structure.

Examples:

stack = DSA::Stack.new
stack.push(1).push(2).push(3)
stack.pop  # => 3
stack.peek # => 2

Instance Method Summary collapse

Constructor Details

#initializeDSA::Stack

Initialize a new empty stack.



12
13
14
# File 'lib/dsa-ruby/stack.rb', line 12

def initialize
  @elements = []
end

Instance Method Details

#empty?Boolean

Checks if the stack is empty.

Examples:

stack = DSA::Stack.new
stack.empty?  # => true

Returns:

  • (Boolean)

    true if the stack contains no elements



67
68
69
# File 'lib/dsa-ruby/stack.rb', line 67

def empty?
  @elements.empty?
end

#peekObject

Returns the value at the top of the stack without removing it.

Examples:

stack.push(1).push(2)
stack.peek  # => 2

Returns:

  • (Object)

    the value at the top of the stack

Raises:

  • (IndexError)

    if the stack is empty



46
47
48
49
# File 'lib/dsa-ruby/stack.rb', line 46

def peek
  raise IndexError, "stack is empty" if empty?
  @elements.last
end

#popObject

Removes and returns the value at the top of the stack.

Examples:

stack.push(1).push(2)
stack.pop  # => 2

Returns:

  • (Object)

    the value at the top of the stack

Raises:

  • (IndexError)

    if the stack is empty



34
35
36
37
# File 'lib/dsa-ruby/stack.rb', line 34

def pop
  raise IndexError, "stack is empty" if empty?
  @elements.pop
end

#push(val) ⇒ DSA::Stack

Pushes a value onto the top of the stack.

Examples:

Push with chaining

stack.push(1).push(2).push(3)

Parameters:

  • val (Object)

    the value to push onto the stack

Returns:



22
23
24
25
# File 'lib/dsa-ruby/stack.rb', line 22

def push(val)
  @elements.push(val)
  self
end

#sizeInteger

Returns the number of elements in the stack.

Examples:

stack.push(1).push(2)
stack.size  # => 2

Returns:

  • (Integer)

    the number of elements



57
58
59
# File 'lib/dsa-ruby/stack.rb', line 57

def size
  @elements.size
end

#to_aArray

Returns a defensive copy of the stack as an array.

Examples:

stack.push(1).push(2).push(3)
stack.to_a  # => [3, 2, 1]

Returns:

  • (Array)

    an array containing all elements in the stack (top to bottom order)



77
78
79
# File 'lib/dsa-ruby/stack.rb', line 77

def to_a
  @elements.dup
end