Singly Linked Lists

Nerly Ton
2 min readApr 5, 2021

--

A short intro to singly linked lists.

Definition: A linked list has nodes and within each node has a value and a pointer to another node/null. Since this is singly linked list then it means it is only connected in one direction. There is no index.
— Singly Linked Lists is good for insertion and deletion

Head: Beginning of list

Tail: End of list

Below you will see the code to write your own linked list.

class Node{
constructor(val){
this.val = val;
this.next = null;
}
}

class SinglyLinkedList{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
push(val){
var newNode = new Node(val);
if(!this.head){
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
pop(){
if(!this.head) return undefined;
var current = this.head;
var newTail = current;
while(current.next){
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
if(this.length === 0){
this.head = null;
this.tail = null;
}
return current;
}
shift(){
if(!this.head) return undefined;
var currentHead = this.head;
this.head = currentHead.next;
this.length--;
if(this.length === 0){
this.tail = null;
}
return currentHead;
}
unshift(val){
var newNode = new Node(val);
if(!this.head) {
this.head = newNode;
this.tail = this.head;
}
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
}

Now for an example problem.

Write a function that returns a modified version of the Linked List that doesn’t contain any nodes with duplicate values.

class LinkedList {
constructor(value) {
this.value = value;
this.next = null;
}
}
function removeDuplicatesFromLinkedList(linkedList) {
let currentNode = linkedList
while (currentNode !== null) {
let nextDistinctNode = currentNode.next
while (nextDistinctNode !== null && nextDistinctNode.value === currentNode.value) {
nextDistinctNode = nextDistinctNode.next
}
currentNode.next = nextDistinctNode
currentNode = nextDistinctNode
}
return linkedList;
}

This is just a simple example on how singly linked lists can be solved. Theres is more to learn and more to practice but I hope having both the code and problem to view has made it easier to understand.

--

--

No responses yet