In this challenge I learned about 2 new data structures; a linked list and a stack and how to implement them by hand. The challenge was specially to create a stack class and then reverse the linked list using this stack.
This part 1 of 3 on linked lists. See my other posts here:
Ruby Linked List Pt2 Reverse using mutation
Ruby Linked List Pt3 Floyd’s Cycle Detection
What is a Linked List
A linked list is linear data structure that consisting of 2 elements. A data element, also known as a node, and a pointer element to the next node. The start or entry point of a linked list is called the head and last node will have a pointer of null.
There are more complex versions of linked lists such as doubly linked list, multiply linked list and circular linked list.
How to Implement a Linked List
Implementing a linked list in Ruby can be achieved like so:
Then we can build up a linked list by creating some nodes and linking them like so:
To output the contents of the linked list we can build a method that uses recursion to traverse the linked list like so:
Fyi an iterative approach could have also been used to output the contents of the linked list.
What is a Stack
The most common way to describe a stack is like a stack of plates. As you wash the plates you put one on top of the other. Then if you need a plate you can only remove the top plate. This is known as Last-In-First-Out (LIFO).
A stack is an abstract data type and has 2 principal operations; push
to add element to the stack and pop
which removes the most recently added element.
My Stack Class Implementation
Now this is where the fun began! I had to create a Stack class and implement the 2 principal operations (methods) of push
and pop
and here it is.
What’s happening here is when a value is pushed onto the stack it will create a new LinkedListNode
using the value, while the pointer will become what @data
was previously, this could be nil or a previously pushed LinkedListNode.
Then when we pop
from the stack it prints @data.value
which is at the top of the stack and then it will set the stack to be the next_node
thus removing the top LinkedListNode
from the stack.
We can use the stack like so:
Reverse the Linked List using a Stack
Reversing the linked list after creating the stack was easy as I knew all I need to do was to traverse the linked list push
ing each value onto the stack until the end of the linked list.
To put it all together and to complete the challenge of reversing the linked list do the following:
The output will look like so:
The full code can be found on my github here