Skip to content

Instantly share code, notes, and snippets.

@sarveshrulz
Last active December 8, 2022 13:24
Show Gist options
  • Save sarveshrulz/95ca035b952af82a13bfba057c12d8fa to your computer and use it in GitHub Desktop.
Save sarveshrulz/95ca035b952af82a13bfba057c12d8fa to your computer and use it in GitHub Desktop.
class Node {
constructor(val) {
this.prev = null;
this.next = null;
this.value = val;
}
}
class Dll {
constructor() {
this.head = null;
this.tail = null;
this.count = 0;
}
addToFirst(val) {
var newnode = new Node(val);
this.count++;
if(!this.head){
this.head = newnode;
this.tail = newnode;
newnode.prev = this.head;
} else {
this.head.prev = newnode;
newnode.next = this.head;
this.head = newnode;
}
}
addToPos(pos, val) {
var newnode = new Node(val);
this.count++;
var curr = this.head;
var i = 1;
while(i < pos-1) {
curr = curr.next;
i++
}
curr.next.prev = newnode;
newnode.next = curr.next;
newnode.prev = curr;
curr.next = newnode;
}
displayFromHead() {
var curr = this.head;
while(curr) {
console.log(curr.value);
curr = curr.next;
}
}
displayFromTail() {
var curr = this.tail;
while(curr) {
console.log(curr.value);
curr = curr.prev;
}
}
}
var dll = new Dll();
dll.addToFirst(30);
dll.addToFirst(20);
dll.addToFirst(10);
dll.addToPos(2, 50);
dll.displayFromHead();
dll.displayFromTail();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment