Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page