In: Computer Science
In javascript fill in the method:
/**
* Gets the node that would come before the new one
created to hold a
* value (also known as the last node that contains a
number less than the
* value).
*
* @param value A value that is going to be
inserted.
* @return The last node that contains a number less
than the value, or null
* if no nodes contain numbers less than the
value.
*/
private Node getPrecedingNode(double value) {
return null; // TODO: Fill in
body.
}
//=================linkedList.js================
class Node {
constructor(element)
{
this.element = element;
this.next = null
}
}
//======================
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
//____________________
insert(element){
// creates a new node
var node = new Node(element);
// to store current node
var current;
if (this.head == null){
this.head =
node;
this.size++;
return;
}
if(element>=this.head.element){
node.next=this.head;
this.head=node;
this.size++;
return;
}
current = this.head;
while (current.next) {
if(element<=current.element &&
element>current.next.element){
node.next=current.next;
//add node
current.next=node;
this.size++;
return;
}
current = current.next;
}
// add node
current.next = node;
this.size++;
}
//____________________
getValue(value){
var current= this.head;
if(current==null)
return
null;
while (current) {
if(current.element<=value)
return current.element;
current=current.next;
}
return null;
}
//_________________
print(){
var current= this.head;
while (current) {
console.log(current.element)
current=current.next;
}
}
} //end of class linkedlist
let list = new LinkedList();
list.insert(45);
list.insert(34);
list.insert(25);
list.insert(49);
console.log("Content of list");
list.print();
console.log("Element just less than 38");
console.log(list.getValue(38));
//============================================
//output