O'Reilly logo

A Common-Sense Guide to Data Structures and Algorithms by Jay Wengrow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required