Find a maximum value in a linked list
// Find a maximum value in a linked list
let node = function(data) {
this.next = null;
this.data = data;
}
let list = function() {
this.head = null;
}
list.prototype.add = function(data) {
if (!this.head) {
this.head = new node(data);
return this.head;
} else {
let curr = this.head;
while(curr.next) {
curr = curr.next;
}
curr.next = new node(data);
return curr.next;
}
}
list.prototype.print = function(name) {
console.log('printing ' + (name ? name : '...'));
let curr = this.head;
while(curr) {
console.log(curr.data);
curr = curr.next;
}
}
list.prototype.getMax = function() {
let curr = this.head;
if (!curr) return null;
let max = curr.data;
while(curr.next) {
if (curr.data > max) max = curr.data;
curr = curr.next;
}
return max;
}
let l = new list();
l.add(9);
l.add(1);
l.add(10);
l.add(1);
// l.print();
console.log('Max: ', l.getMax());