Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Last active March 20, 2022 10:12
Show Gist options
  • Save mustafadalga/9b40acae53156082376fda6ab0bd38e7 to your computer and use it in GitHub Desktop.
Save mustafadalga/9b40acae53156082376fda6ab0bd38e7 to your computer and use it in GitHub Desktop.
class Node {
constructor(val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(val) {
const newNode = new Node(val);
if (this.length == 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
}
pop() {
if (!this.head) return undefined;
const currentTail = this.tail;
if (this.length == 1) {
this.head = null;
this.tail = null;
} else {
this.tail = currentTail.prev;
this.tail.next = null;
currentTail.prev = null;
}
this.length--;
return currentTail;
}
shift() {
if (this.length == 0) return undefined;
let oldHead = this.head;
if (this.length == 1) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
this.head.prev = null;
oldHead.next = null;
}
this.length--;
return oldHead;
}
unshift(val) {
const newNode = new Node(val);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
this.head.prev = newNode;
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return this;
}
get(index) {
if (index < 0 || index >= this.length) return null;
let count, currentNode;
if (index < (this.length / 2)) {
count = 0;
currentNode = this.head;
while (count < index) {
currentNode = currentNode.next;
count++;
}
} else {
currentNode = this.tail;
count = this.length - 1;
while (index < count) {
currentNode = currentNode.prev;
count--;
}
}
return currentNode;
}
set(index, val) {
const node = this.get(index);
if (node) {
node.val = val;
return true;
}
return false;
}
insert(index, val) {
if (index < 0 || index >= this.length) return false;
else if (index == 0) return !!this.unshift(val);
else if (index == this.length) return !!this.push(val);
const newNode = new Node(val);
const prevNode = this.get(index - 1);
const tempNextNode = prevNode.next;
prevNode.next = newNode;
newNode.next = tempNextNode;
newNode.prev = prevNode;
tempNextNode.prev = newNode;
this.length++;
return true;
}
remove(index) {
if (index < 0 || index >= this.length) return undefined;
if (index == this.length - 1) return !!this.pop();
if (index == 0) return !!this.shift();
const prevNode = this.get(index - 1);
const currentNode = prevNode.next;
const nextNode = currentNode.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
currentNode.prev = null;
currentNode.next = null;
this.length--;
return currentNode;
}
}
const list = new DoublyLinkedList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment