Stack Implementation in Ruby

1. Introduction

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle, meaning the last element added to the stack is the first to be removed. 

Common operations associated with a stack include push, which adds an element to the top of the stack, and pop, which removes the topmost element.

2. Implementation Steps

1. Define the Stack class and initialize an empty list (or array in Ruby) to store elements.

2. Implement the push method to add an element to the top of the stack.

3. Implement the pop method to remove and return the topmost element from the stack.

4. Implement the peek method to view the topmost element without removing it.

5. Implement a method to check if the stack is empty.

3. Implementation in Ruby Programming

class Stack
    def initialize
        @items = [] # Initializing an empty array to store the stack elements
    end
    # Pushing an item onto the stack
    def push(item)
        @items.push(item)
    end
    # Popping the topmost item off the stack
    def pop
        @items.pop
    end
    # Peeking at the topmost item without removing it
    def peek
        @items.last
    end
    # Checking if the stack is empty
    def is_empty?
        @items.empty?
    end
end
# Client code
stack = Stack.new
stack.push(5)
stack.push(10)
puts "Top of the stack: #{stack.peek}"  # Output: 10
stack.pop
puts "Top of the stack after pop: #{stack.peek}"  # Output: 5

Output:

Top of the stack: 10
Top of the stack after pop: 5

Explanation:

1. The Stack class is initialized with an empty array @items that will be used to store the stack's elements.

2. The push method adds an element to the end (or top) of the @items array.

3. The pop method removes and returns the last element (or top) from the @items array.

4. The peek method returns the last element (or top) from the @items array without removing it.

5. The is_empty? method checks if the @items array is empty, indicating that the stack is empty.


Comments