JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<!-- <p>Remove Dupes</p>
<p>write code to remove duplicates from an unsorted linked list</p> -->

JavaScript

/*
We’d use a linked list over an array when we need faster insertion and deletion, but we can tolerate slow item retrieval and we’re o.k. with extra space taken up. If we’re space-limited or access speed is important, we’d use an array.
*/

class Node {
	constructor(value, next) {
  	this.value = value;
    this.next = next;
  }
}

class LinkedList {
	constructor(value) {
  	this.head = {
    	value,
      next: null
    }
    
    this.length = 1;
  }
  
  addToHead(value) {
  	const newNode = {
    	value,
      next: this.head
    }
    
    this.head = newNode;
    this.length++;
    return this;
  }
  
  removeFromHead() {
  	if (this.length === 0) {
    	return undefined;
    }

  	const removedValue = this.head.value;
  	this.head = this.head.next;
    this.length--;
    return removedValue;
  }
  
  find(val) {
  	let thisNode = this.head;
    
    while (thisNode) {
    	if (thisNode.value === val) {
      	return thisNode;
      }
      
      thisNode = thisNode.next;
    }
    
    return thisNode;
  }
  
  remove(val) {
  	if (this.length === 0) {
    	return undefined;
    }
    
    if (this.head.value === val) {
    	return this.removeFromHead();
    }
    
    let previousNode = this.head;
    let currentNode = this.head.next;
    
    while (currentNode) {
    	if (currentNode.value === val) {
				break;
      }
			
      previousNode = currentNode;
      currentNode = currentNode.next;
    }
    
    if (currentNode === null) {
			return undefined;
    }
    
    previousNode.next = currentNode.next;
    this.length--;
    return this;
  }
}

const list = new LinkedList(1);
list.addToHead(2);
list.addToHead(3);
alert(JSON.stringify(list));