Data Structures Decoded: Singly Linked Lists IV
2 min readFeb 15, 2021
Data structures: the other cornerstone of a competent software engineer. This is why I’m compiling all my research and work on the topic in a series of articles titled Data Structures Decoded.
Previously on Data Structures Decoded…
In the second part of our look at Singly Linked Lists, we created a .shift() instance method.
In today’s article, we’ll be exploring how to add an .unshift() function to our Singly Linked List class.
Let’s Unshift Gears
Here’s the pseudocode:
- The function should accept a value
- Create a new node using the value passed to the function
- If there is no head property on the list, set the head and tail to be newly created node
- Otherwise, set the newly created node’s next property to be the current head property on the list
- Set the head property on the list to be that newly created node
- Increment the length of the list by 1
- Return the linked list
And for the main event…
unshift(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return this;
}
What do you think? If you liked what you read, consider connecting or dropping me a line at nick.echev AT gmail.com!