Last active
August 11, 2024 04:22
-
-
Save kshirish/ba4dd1eb5f089874eb57182be9b400a4 to your computer and use it in GitHub Desktop.
with head & tail
This file contains hidden or 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
// 2 -> 8 -> 10 -> 4 -> 7 | |
// {value, next} | |
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class LinkedList { | |
constructor(mainNode) { | |
this.headNode = this.tailNode = mainNode; | |
} | |
add(node) { | |
this.tailNode.next = node; | |
this.tailNode = node | |
} | |
insert(value, beforeValue) { | |
let pointer = this.headNode; | |
const node = new Node(value); | |
while(pointer.next) { | |
pointer = pointer.next; | |
if(pointer.value === beforeValue) { | |
if(beforeValue === this.tailNode.value) { | |
this.tailNode = node; | |
} | |
node.next = pointer.next; | |
pointer.next = node; | |
} | |
} | |
} | |
remove(value) { | |
let pointer = this.headNode; | |
while(pointer.next) { | |
if(pointer.next.value === value) { | |
if(pointer.next === this.tailNode) { | |
this.tailNode = pointer; | |
} else { | |
pointer.next = pointer.next.next; | |
} | |
} else { | |
pointer = pointer.next; | |
} | |
} | |
} | |
printAll() { | |
let pointer = this.headNode; | |
let str = this.headNode.value + ' -> '; | |
while(pointer.next) { | |
pointer = pointer.next; | |
str += pointer.value + ' -> '; | |
} | |
console.log(str); | |
} | |
} | |
const headNode = new Node('HEAD'); // {'HEAD', null} | |
const ll = new LinkedList(headNode); | |
ll.add(new Node(2)); | |
ll.add(new Node(8)); | |
ll.add(new Node(10)); | |
ll.add(new Node(4)); | |
ll.add(new Node(7)); | |
ll.printAll(); | |
ll.remove(7); | |
ll.add(new Node(33)); | |
ll.printAll(); | |
ll.insert(100, 4); | |
ll.printAll(); | |
ll.insert(55, 33); | |
ll.printAll(); | |
ll.add(new Node(1)); | |
ll.printAll(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment