Doubly-Linked Lists
A doubly-linked list is a type of linked list where each element contains pointers to both the next and previous elements in the sequence. This allows for traversal in both forward and backward directions. Doubly-linked lists support efficient insertion and deletion operations at both ends of the list.
Below is the Ruby program to implement a doubly-linked list:
class Node
attr_accessor :value, :next, :prev
def initialize(value)
@value = value
@next = nil
@prev = nil
end
end
class DoublyLinkedList
def initialize
@head = nil
@tail = nil
end
def append(value)
if @head.nil?
@head = Node.new(value)
@tail = @head
else
new_node = Node.new(value)
new_node.prev = @tail
@tail.next = new_node
@tail = new_node
end
end
def display_forward
current = @head
while current
puts current.value
current = current.next
end
end
def display_backward
current = @tail
while current
puts current.value
current = current.prev
end
end
end
list = DoublyLinkedList.new
list.append(1)
list.append(2)
list.append(3)
list.display_forward
puts "--------"
list.display_backward
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