Add linked lists
by Anton Bagayev
HTML
<p id="list1"></p>
<p id="list2"></p>
<p id="output"></p>
JavaScript
let Node = function() {
this.value = undefined;
this.next = undefined;
}
let LinkedList = function() {
this.head = undefined;
}
LinkedList.prototype.add = function(value) {
let node = new Node();
node.value = value;
node.next = this.head;
this.head = node;
}
LinkedList.prototype.length = function(){
let result = 0;
let currNode = this.head;
while (currNode){
result++;
currNode = currNode.next;
}
return result;
}
function printList(list) {
let currNode = list.head;
let result = "";
while (currNode !== undefined){
result += currNode.value;
currNode = currNode.next;
if (currNode) {
result += "->";
}
}
return result;
}
let carryOver = 0;
let resultList = new LinkedList();
function addSameLengthLists(node1, node2){
if (node1 == undefined){
return;
}
addSameLengthLists(node1.next, node2.next);
let sum = node1.value + node2.value + carryOver;
carryOver = Math.floor(sum / 10);
sum %= 10;
resultList.add(sum);
}
function addLists(list1, list2) {
let length1 = list1.length();
let length2 = list2.length();
if (length1 == 0) {
return list2;
}
if (length2 == 0) {
return list1;
}
if (length1 == length2) {
addSameLengthLists(list1.head, list2.head);
}
return resultList;
}
let list1 = new LinkedList();
list1.add(3);
list1.add(6);
list1.add(5);
let list2 = new LinkedList();
list2.add(3);
list2.add(2);
list2.add(4);
document.getElementById('list1').innerText = printList(list1);
document.getElementById('list2').innerText = printList(list2);
document.getElementById('output').innerText = printList(addLists(list1,list2));