Skip to content

Instantly share code, notes, and snippets.

@Louiefigz
Created July 29, 2020 16:46
Show Gist options
  • Save Louiefigz/0ecc42321f008831647603adcb81de87 to your computer and use it in GitHub Desktop.
Save Louiefigz/0ecc42321f008831647603adcb81de87 to your computer and use it in GitHub Desktop.
Linked Lists
class Node {
constructor(data, next = null){
this.data = data;
this.next = next;
}
}
class LinkedList{
constructor(){
this.head = null;
}
insertFirst(record){
this.head = new Node(record, this.head);
// console.log(this.head.next);
}
size(){
let counter = 0;
let node = this.head;
while (node) {
counter++
node = node.next;
}
return counter;
}
getLast(){
let node = this.head;
while (node) {
if (!node.next){
return node;
}
node = node.next;
}
return node;
}
clear(){
this.head = null;
}
removeFirst(){
if (!this.head){
return null;
}
if (!this.head.next){
return null;
}
return this.head = this.head.next;
}
removeLast(){
if (!this.head){
return null;
}
if (!this.head.next){
return this.head = null;
}
let node = this.head;
let prev;
while (node.next) {
prev = node;
node = node.next;
}
prev.next = null;
return this.head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment