In: Computer Science
This all has to be in javascript
Use this linked list to answer the questions below:
var list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
1. We are going to extend LinkedList with a sum method. As the name implies, all elements in the linked list should be summed together. First, write a few tests that will eventually show your code works correctly (after you implement the function in (2)). Note: see the LinkedList implementation above for more details. Hint: note that the sum of the elements in list above is 10.
2. Finish the implementation of the sum function below. As the name implies, all elements in the linked list should be summed together. Return null if there are no elements in the list. Make sure to validate your code using the tests from (1).
LinkedList.prototype.sum = function() {
note: use 'this' to refer to the linked list, e.g., this.getHead()
};
// User defined class node
class Node {
// constructor
constructor(element) {
this.element = element;
this.next = null
}
}
// linkedlist class
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// append element at the end of list
append(element) {
// creates a new node
var node = new Node(element);
// to store current node
var current;
// if list is Empty add the
// element and make it head
if (this.head == null)
this.head = node;
else {
current = this.head;
// iterate to the end of the list
while (current.next) {
current = current.next;
}
// add node
current.next = node;
}
this.size++;
}
}
// Extending LinkedList with sum method
class LinkedLists extends LinkedList {
sum() {
// To store sum
var s = 0;
// To store current node
var current = this.head;
if (current == null) {
return null;
}
while (current) {
s += current.element;
current = current.next;
}
return s;
}
}
var list = new LinkedLists();
console.log(list.sum()) // Output: null
list.append(1);
console.log(list.sum()) // Output: 1
list.append(2);
console.log(list.sum()) // Output: 3
list.append(3);
console.log(list.sum()) // Output: 6
list.append(4);
console.log(list.sum()) // Output: 10
Go through this and let me know through comments if you have any doubts about this.
Please give a thumbs up if you are satisfied with the Answer.
Thank you!!!