Skip to content

Instantly share code, notes, and snippets.

@ChickenFur
Last active November 23, 2019 19:15
Show Gist options
  • Save ChickenFur/ee396bb3545d9b959ca1ad7841c1ea82 to your computer and use it in GitHub Desktop.
Save ChickenFur/ee396bb3545d9b959ca1ad7841c1ea82 to your computer and use it in GitHub Desktop.
Submission 2
class ListNode {
val: number | null;
next: ListNode | null;
constructor(numbers: Array<number>) {
for (var i = 0; i < numbers.length; i++) {
this.val = numbers[0];
if (i + 1 === numbers.length) {
this.next = null;
} else {
this.next = new ListNode(numbers.splice(i + 1));
}
}
}
extract(resultArray) {
resultArray.push(this.val);
while (this.next) {
return this.next.extract(resultArray);
}
}
}
const addTwoNumbers = (l1: ListNode, l2: ListNode) => {
var result = new ListNode([]);
var l1CurrentNode = l1;
var l2CurrentNode = l2;
var currentResultNode = result;
while (true) {
const val1 = l1CurrentNode?.val || 0;
const val2 = l2CurrentNode?.val || 0;
const newValue = val1 + val2 + (currentResultNode.val || 0);
console.log(newValue);
if (newValue > 9) {
currentResultNode.val = newValue % 10;
currentResultNode.next = new ListNode([Math.floor(newValue / 10)]);
} else {
currentResultNode.val = newValue;
}
l1CurrentNode = l1CurrentNode?.next;
l2CurrentNode = l2CurrentNode?.next;
if (l1CurrentNode == null && l2CurrentNode == null) {
break;
}
if (!currentResultNode.next) {
currentResultNode.next = new ListNode([]);
}
currentResultNode = currentResultNode.next;
}
const resultArray = [];
result.extract(resultArray);
console.log("result", resultArray);
return result;
};
addTwoNumbers(new ListNode([1]), new ListNode([9, 9]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment