Last active
November 1, 2023 15:44
-
-
Save tulusibrahim/3e39acf4ab81062146f104c7d21897a1 to your computer and use it in GitHub Desktop.
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(val) { | |
this.val = val; | |
this.next = null; | |
} | |
} | |
class linkedList { | |
#size = 0; | |
#head = null; | |
constructor() { | |
this.#size = 0; | |
this.#head = null; | |
} | |
length() { | |
return this.#size; | |
} | |
get(index) { | |
let curr = this.#head | |
let count = 0 | |
while(count < index) { | |
curr = curr.next | |
count++ | |
} | |
return curr.val | |
} | |
append(val) { | |
this.#size += 1; | |
let node = new Node(val); | |
if (this.#head == null) { | |
this.#head = node; | |
} else { | |
let curr = this.#head; | |
while (curr.next !== null) { | |
curr = curr.next; | |
} | |
curr.next = node; | |
} | |
} | |
prepend(val) { | |
this.#size += 1; | |
let node = new Node(val); | |
let curr = this.#head; | |
node.next = curr; | |
this.#head = node; | |
} | |
insertAt(val, index) { | |
if (index > this.#size) throw new Error('Index is out of bound'); | |
let count = 1; | |
let curr = this.#head; | |
let node = new Node(val); | |
if (index == 0) { | |
this.prepend(val); | |
return; | |
} | |
while (curr.next) { | |
if (count == index) break; | |
curr = curr.next; | |
count++; | |
} | |
node.next = curr.next; | |
curr.next = node; | |
this.#size += 1; | |
} | |
removeAt(index) { | |
let count = 1; | |
let curr = this.#head; | |
if(index >= this.#size) throw new Error('Index is out of bound') | |
if(index == 0) { | |
this.#head = this.#head.next | |
this.#size-=1 | |
return | |
} | |
while (curr.next && count < index) { | |
curr = curr.next; | |
count++ | |
} | |
curr.next = curr.next.next; | |
this.#size-=1 | |
} | |
entries() { | |
let temp = []; | |
let curr = this.#head; | |
while (curr.next) { | |
temp.push(curr.val); | |
curr = curr.next; | |
} | |
temp.push(curr.val); | |
return temp; | |
} | |
} | |
const ll = new linkedList(); | |
ll.append(1); | |
ll.append(2); | |
ll.append(3); | |
ll.prepend(5); | |
ll.prepend(50); | |
ll.insertAt(25, 5); | |
ll.insertAt(20, 0); | |
ll.insertAt(30, 6); | |
console.log(ll.entries()); | |
console.log('val at idx 6: ',ll.get(6)) | |
ll.removeAt(0); | |
console.log(ll.entries()); | |
console.log('len: ',ll.length()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment