Created
July 29, 2020 16:46
-
-
Save Louiefigz/0ecc42321f008831647603adcb81de87 to your computer and use it in GitHub Desktop.
Linked Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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