August 2017
Intermediate to advanced
222 pages
5h 3m
English
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 ...