File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
snippets/ruby/data-structures Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ title : Singly Linked List
3+ description : Implements a basic singly linked list with node insertion and traversal.
4+ author : ACR1209
5+ tags : ruby,data structures,linked list
6+ ---
7+
8+ ``` rb
9+ class Node
10+ attr_accessor :data , :next
11+
12+ def initialize (data )
13+ @data = data
14+ @next = nil
15+ end
16+ end
17+
18+ class LinkedList
19+ def initialize
20+ @head = nil
21+ end
22+
23+ def append (data )
24+ new_node = Node .new (data)
25+ if @head .nil?
26+ @head = new_node
27+ else
28+ current = @head
29+ current = current.next while current.next
30+ current.next = new_node
31+ end
32+ end
33+
34+ def display
35+ current = @head
36+ while current
37+ print " #{ current.data } -> "
38+ current = current.next
39+ end
40+ puts " nil"
41+ end
42+ end
43+
44+ # Usage:
45+ list = LinkedList .new
46+ list.append(1 )
47+ list.append(2 )
48+ list.append(3 )
49+ list.display # Output: 1 -> 2 -> 3 -> nil
50+ ```
You can’t perform that action at this time.
0 commit comments