Given an integer value x, how to search a linked list and delete all nodes with data value greater than x?
How to optimally do this in Javascript?
Update on 2016-11-17
I am implementing the list in javascript like this:
function llist() {
this.head = null;
this.tail = null;
this.makeNode = function (data) {
return {data: data, next: null}
};
this.addNode = function (data) {
if (this.head == null) {
this.tail = this.makeNode(data);
this.head = this.tail;
//this.head = this.makeNode(data);
} else {
this.tail.next = this.makeNode(data);
this.tail = this.tail.next;
}
};
}
The tricky part in deletion of a node in linked list is that , you have to handle it differently for head, middle and tail.
this.searchRemoveNodes = function (val) {
var current = this.head;
var prev = null;
while (current != null) {
if (current.data > val) {
if (current == this.head)
this.head = current.next;
else if (current.next == null)
prev.next = null;
else
prev.next = current.next;
current = current.next;
} else {
prev = current;
current = current.next;
}
}
};
Something like this?
It Works!! Thanks!!
Is this a singly linked list or doubly linked list?