fix(JavaScript): doubly link list (#598)

pull/591/head^2
atulll 2021-10-19 19:55:09 +05:30 committed by GitHub
parent 2f6eece500
commit 16f7a0793c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 5 deletions

View File

@ -1,4 +1,3 @@
function DoubleLinkedList() { function DoubleLinkedList() {
const Node = function(element) { const Node = function(element) {
this.element = element; this.element = element;
@ -18,7 +17,6 @@ function DoubleLinkedList() {
tail.next = node; tail.next = node;
tail = node; tail = node;
length++; length++;
}; };
@ -53,6 +51,7 @@ function DoubleLinkedList() {
// look for out-of-bounds value // look for out-of-bounds value
if (position > -1 && position < length) { if (position > -1 && position < length) {
let removedNode;
let current = head; let current = head;
let index = 0; let index = 0;
@ -60,14 +59,23 @@ function DoubleLinkedList() {
current = current.next; current = current.next;
index++; index++;
} }
if (current.next) {
removedNode = current.next;
}
if (current.next.next !== null) { if (current.next.next !== null) {
current.next.next.prev = current; current.next.next.prev = current;
} }
current.next = current.next.next; current.next = current.next.next;
// if current.next is null, that means it
// is the last elem, so let's mark it as tail.
if (!current.next) {
tail = current;
}
length--; length--;
return current.element; return removedNode.element;
} else { } else {
return null; return null;
} }
@ -143,7 +151,6 @@ function DoubleLinkedList() {
}; };
} }
const newDoubleLinkedList = new DoubleLinkedList(); const newDoubleLinkedList = new DoubleLinkedList();
newDoubleLinkedList.append(1); newDoubleLinkedList.append(1);
newDoubleLinkedList.append(5); newDoubleLinkedList.append(5);
@ -156,4 +163,5 @@ console.log(newDoubleLinkedList.toArray());
console.log(newDoubleLinkedList.toString()); console.log(newDoubleLinkedList.toString());
newDoubleLinkedList.delete(20); newDoubleLinkedList.delete(20);
console.log('After delete 20: '+newDoubleLinkedList.toString()); console.log('After delete 20: ' + newDoubleLinkedList.toString());
console.log(`Tail points to : ${newDoubleLinkedList.getTail().element}`);