Circular Linked Lists
A circular linked list is a variation of a linked list where the last element points back to the first element, forming a circular structure. This can be achieved by making the next pointer of the last node point to the first node. Circular linked lists can be singly or doubly-linked and are useful for applications like managing circular buffers or implementing algorithms like Floyd’s cycle detection algorithm.
Below is the Ruby program to implement a circular-linked list:
class Node
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
end
class CircularSinglyLinkedList
def initialize
@head = nil
end
def append(value)
if @head.nil?
@head = Node.new(value)
@head.next = @head # Make it circular
else
current = @head
while current.next != @head
current = current.next
end
current.next = Node.new(value)
current.next.next = @head # Make it circular
end
end
def display
current = @head
loop do
puts current.value
current = current.next
break if current == @head
end
end
end
list = CircularSinglyLinkedList.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