Singly Linked Lists

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;
}
}
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;
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

JavaScript Ninja — Putting a hole in console.log using kind of proxy pattern

How to Create a Carousel In React!!!

Create Objects Using Object Constructors in JavaScript

Track your NGRX Actions State

Angular 9 — Change Detection with Pipe and OnPush Strategy

The Angular Library Series - Creating a Library with the Angular CLI

Web Scraping 101: Cheerio with Node to the Rescue

Building a User Registration and Login with VUE and Firebase Auth

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nerly Ton

Nerly Ton

More from Medium

How I survived fighting with A military personnel in hand to hand combat

Tribute to Don Bandler