This post just posts the code for the solution for the sum lists problem on Linkedlist. You can see that question here,
https://leetcode.com/problems/add-two-numbers/
Now onto the code
https://leetcode.com/problems/add-two-numbers/
Now onto the code
class LinkedListNode {
next: LinkedListNode = null;
data: number;
constructor(data?: number, next?: LinkedListNode) {
this.data = data;
this.next = next;
}
appendToTail(d: number) {
let end = new LinkedListNode(d);
let n: LinkedListNode = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
length(): number {
var len = 1;
var current = this.next;
while (current != null) {
len += 1;
current = current.next;
}
return len;
}
}
class LinkedlistService {
sumLists(l1: LinkedListNode, l2: LinkedListNode, carry: number): LinkedListNode {
if (l1 == null && l2 == null && carry == 0) {
return null;
}
var result: LinkedListNode = new LinkedListNode();
var value = carry;
if (l1 != null) {
value += l1.data;
}
if (l2 != null) {
value += l2.data;
}
result.data = value % 10;
//recurse
if (l1 != null || 12 != null) {
var more: LinkedListNode = this.sumLists(l1 == null ? null : l1.next,
l2 == null ? null : l2.next,
value >= 10 ? 1 : 0);
result.next = more;
}
return result;
}
}
No comments:
Post a Comment