I want to build doubly linkedList from singly linkedList
and the output is [1,10,5,16].
I think the problem is in append,insert and remove function
Could someone help me to change singly linkedList?
What i know about doubly linkedList is there are two node
one point to the next value
second point to the previous value
Here is my JS:
class DoublyLinkedList {
constructor(value) {
this.head = {
value: value,
previous:null,
next: null
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = {
value: value,
previous:null,
next: null
}
this.tail.next = newNode;
newNode.previous=this.head
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = {
value: value,
next: null
}
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList() {
const array = [];
let currentNode = this.head;
while(currentNode !== null){
array.push(currentNode.value)
currentNode = currentNode.next
}
return array;
}
insert(index, value){
//Check for proper parameters;
if(index >= this.length) {
console.log('yes')
return this.append(value);
}
const newNode = {
value: value,
next: null
previous:null
}
const leader = this.traverseToIndex(index-1);
const holdingPointer = leader.next;
leader.next = newNode;
newNode.previous = this.head
newNode.next = holdingPointer;
this.length++;
return this.printList();
}
traverseToIndex(index) {
//Check parameters
let counter = 0;
let currentNode = this.head;
while(counter !== index){
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
remove(index) {
// Check Parameters
const leader = this.traverseToIndex(index-1);
const unwantedNode = leader.next;
unwantedNode.previous=leader.head;
leader.next = unwantedNode.next;
this.length--;
return this.printList();
}
}
let myDoublyLinkedList = new DoublyLinkedList(10);
myDoublyLinkedList.append(5);
myDoublyLinkedList.append(16);
myDoublyLinkedList.prepend(1);
myDoublyLinkedList.insert(2, 6);
myDoublyLinkedList.remove(2);//Should return [1,10,5,16]