Implementing a Linked List

Let’s implement a linked list using Ruby. We’ll use two classes to implement this: Node and LinkedList. Let’s create the Node class first:

 class​ Node
 
  attr_accessor ​:data​, ​:next_node
 
 def​ ​initialize​(data)
  @data = data
 end
 
 end

The Node class has two attributes: data contains the value that the node is meant to hold, while next_node contains the link to the next node in the list. We can use this class as follows:

 node_1 = Node.​new​(​"once"​)
 node_2 = Node.​new​(​"upon"​)
 node_1.​next_node​ = node_2
 
 node_3 = Node.​new​(​"a"​)
 node_2.​next_node​ = node_3
 
 node_4 = Node.​new​(​"time"​)
 node_3.​next_node​ = node_4

With this code, we’ve created a list of four nodes that serve as a list ...

Get A Common-Sense Guide to Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.