Class: DSA::Stack
- Inherits:
-
Object
- Object
- DSA::Stack
- Defined in:
- lib/dsa-ruby/stack.rb
Overview
DSA::Stack - Last-In-First-Out (LIFO) data structure.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Checks if the stack is empty.
-
#initialize ⇒ DSA::Stack
constructor
Initialize a new empty stack.
-
#peek ⇒ Object
Returns the value at the top of the stack without removing it.
-
#pop ⇒ Object
Removes and returns the value at the top of the stack.
-
#push(val) ⇒ DSA::Stack
Pushes a value onto the top of the stack.
-
#size ⇒ Integer
Returns the number of elements in the stack.
-
#to_a ⇒ Array
Returns a defensive copy of the stack as an array.
Constructor Details
#initialize ⇒ DSA::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.
67 68 69 |
# File 'lib/dsa-ruby/stack.rb', line 67 def empty? @elements.empty? end |
#peek ⇒ Object
Returns the value at the top of the stack without removing it.
46 47 48 49 |
# File 'lib/dsa-ruby/stack.rb', line 46 def peek raise IndexError, "stack is empty" if empty? @elements.last end |
#pop ⇒ Object
Removes and returns the value at the top of the stack.
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.
22 23 24 25 |
# File 'lib/dsa-ruby/stack.rb', line 22 def push(val) @elements.push(val) self end |
#size ⇒ Integer
Returns the number of elements in the stack.
57 58 59 |
# File 'lib/dsa-ruby/stack.rb', line 57 def size @elements.size end |
#to_a ⇒ Array
Returns a defensive copy of the stack as an array.
77 78 79 |
# File 'lib/dsa-ruby/stack.rb', line 77 def to_a @elements.dup end |