File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
snippets/ruby/data-structures Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ title : Doubly Linked List
3+ description : Implements a doubly linked list with node insertion and traversal.
4+ author : ACR1209
5+ tags : ruby,data structures,linked list,doubly linked list
6+ ---
7+
8+ ``` rb
9+ class Node
10+ attr_accessor :data , :next , :prev
11+
12+ def initialize (data )
13+ @data = data
14+ @next = nil
15+ @prev = nil
16+ end
17+ end
18+
19+ class DoublyLinkedList
20+ def initialize
21+ @head = nil
22+ @tail = nil
23+ end
24+
25+ def append (data )
26+ new_node = Node .new (data)
27+ if @head .nil?
28+ @head = new_node
29+ @tail = new_node
30+ else
31+ @tail .next = new_node
32+ new_node.prev = @tail
33+ @tail = new_node
34+ end
35+ end
36+
37+ def prepend (data )
38+ new_node = Node .new (data)
39+ if @head .nil?
40+ @head = new_node
41+ @tail = new_node
42+ else
43+ new_node.next = @head
44+ @head .prev = new_node
45+ @head = new_node
46+ end
47+ end
48+
49+ def display_forward
50+ current = @head
51+ while current
52+ print " #{ current.data } <-> "
53+ current = current.next
54+ end
55+ puts " nil"
56+ end
57+
58+ def display_backward
59+ current = @tail
60+ while current
61+ print " #{ current.data } <-> "
62+ current = current.prev
63+ end
64+ puts " nil"
65+ end
66+ end
67+
68+ # Usage:
69+ dll = DoublyLinkedList .new
70+ dll.append(1 )
71+ dll.append(2 )
72+ dll.append(3 )
73+ dll.display_forward # Output: 1 <-> 2 <-> 3 <-> nil
74+ dll.display_backward # Output: 3 <-> 2 <-> 1 <-> nil
75+ ```
You can’t perform that action at this time.
0 commit comments