I am facing a problem in the remove element in the list. When I want to remove the element in the list it not able to remove but other function works properly such as adding and removing at index.
class Node{
constructor(element){
this.element = element;
this.right = null;
this.left = null;
}
}
class DLinkList{
constructor(){
this.head = null;
this.tail = null;
this.size = 0;
}
addFront(element){
var node = new Node(element);
var curr;
if(this.head === null){
this.head = node;
this.tail = node;
}else{
this.head.left = node;
node.right = this.head;
this.head = node;
}
this.size++;
}
addAtIndex(element,index){
var node = new Node(element);
var curr,prev;
if(this.head === null){
this.head = node;
this.tail = node;
}else{
var it = 0;
curr = this.head;
while(it < index){
it++;
prev = curr;
curr = curr.right;
}
node.right = curr;
prev.right = node;
node.left = prev;
}
this.size++;
}
removeAtIdex(index){
var curr,prev, it = 0;
if(index > 0 && index > this.size){
return false;
}else{
curr = this.head;
while(it < index){
it++;
prev = curr;
curr = curr.right;
}
prev.right = curr.right;
curr.right.left = prev;
}
this.size--;
}
removeElement(element){
var curr,prev = null;
curr = this.head;
while(curr != null){
if(curr.element === element){
if(prev === null){
this.head = curr.right;
}else{
prev.right = curr.right;
}
this.size--;
}
prev = curr;
curr = curr.next;
}
return -1;
}
printList(){
var curr = this.head;
var str = ''
while(curr){
str += curr.element + ' ';
curr = curr.right;
}
console.log(str);
}
}
var ll = new DLinkList();
ll.addFront(2);
ll.addFront(3);
ll.addFront(4);
ll.addAtIndex(5,2);
ll.printList();
ll.removeAtIdex(1);
ll.printList();
ll.removeElement(5);
ll.printList();
console.log(ll);
output:
4 3 5 2
4 5 2
4 5 2
DLinkList {
head: Node {
element: 4,
right: Node { element: 5, right: [Node], left: [Circular] },
left: null
},
tail: Node {
element: 2,
right: null,
left: Node { element: 3, right: [Node], left: [Node] }
},
size: 3
}
You use a non-existing property name: next
. There is no curr.next
. It should be curr.right
.
Also, don't forget to update left
and tail
:
if (curr.right === null) {
this.tail = prev;
} else {
curr.right.left = prev;
}