Skip to content

Commit d6364c6

Browse files
committed
Add Ruby snippet for implementing a singly linked list with node insertion and traversal
1 parent 88fcb81 commit d6364c6

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
```

0 commit comments

Comments
 (0)