Singly-Linked Lists
A singly linked list is a linear data structure consisting of a sequence of elements, where each element points to the next element in the sequence. The last element points to nil, indicating the end of the list. Singly-linked lists are simple to implement and efficient for operations such as insertion and deletion at the beginning of the list.
Below is the Ruby program to implement a singly-linked list:
class Node
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
end
class SinglyLinkedList
def initialize
@head = nil
end
def append(value)
if @head.nil?
@head = Node.new(value)
else
current = @head
while current.next
current = current.next
end
current.next = Node.new(value)
end
end
def display
current = @head
while current
puts current.value
current = current.next
end
end
end
list = SinglyLinkedList.new
list.append(1)
list.append(2)
list.append(3)
list.display
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