Stack
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. In a stack, elements are inserted and removed from the same end, called the top of the stack. It operates similarly to a stack of plates where you can only add or remove the top plate.
Below is the Ruby program to implement a stack:
class Stack
def initialize
@elements = []
end
def push(item)
@elements.push(item)
end
def pop
@elements.pop
end
def empty?
@elements.empty?
end
end
# Example Usage
stack = Stack.new
stack.push(1)
stack.push(2)
stack.push(3)
puts stack.pop # Output: 3
puts stack.pop # Output: 2
puts stack.empty? # Output: false
puts stack.pop # Output: 1
puts stack.empty? # Output: true
Output:
How to Implement Data Structures in Ruby?
Data structures are fundamental components of any programming language, allowing developers to organize and manipulate data efficiently. In Ruby, a versatile and expressive language, implementing various data structures is straightforward. In this article, we’ll explore how to implement common data structures such as arrays, linked lists, stacks, queues, trees, graphs, and hashmaps in Ruby. The article focuses on discussing data structures in Ruby.
Table of Content
- Singly-Linked Lists
- Doubly-Linked Lists
- Circular Linked Lists
- Queues
- Stack
- Hash Tables
- Sets
- Binary Trees
- AVL Trees (Adelson-Velsky and Landis Trees)
- Graphs
- Persistent Lists
Contact Us