I am trying to add two numbers in the form of linked List and return their result in a Linked List as given in https://leetcode.com/problems/add-two-numbers/
Question:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807, my solution has solved all the test cases but after refactoring, it is taking longer than the original code
Solution 1:
//public class ListNode
//{
// public int val;
// public ListNode next;
// public ListNode(int x) { val = x; }
//};
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = null;
int carry = 0;
while (l1 != null || l2 != null) {
int first = 0,
second = 0;
if (l1 != null) {
first = l1.val;
l1 = l1.next;
}
if (l2 != null) {
second = l2.val;
l2 = l2.next;
}
int Digit = first + second;
if (carry != 0) {
Digit = Digit + carry;
carry = 0;
}
if (Digit > 9) {
carry = Digit / 10;
Digit = Digit % 10;
}
AddLastNode(Digit, ref l3);
}
if (carry != 0) {
AddLastNode(carry, ref l3);
carry = 0;
}
return l3;
}
/// In here I am looping through the Linked List every time,to find the tail node
private static void AddLastNode(int Digit, ref ListNode l3) {
if (l3 != null) {
AddLastNode(Digit, ref l3.next);
}
else {
l3 = new ListNode(Digit);
}
}
}
So to avoid looping through all the Nodes,in the below solution I am using a reference for the Tail Node
Solution 2:
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = null;
ListNode tailNode = null;
int remainder = 0;
while (l1 != null || l2 != null) {
int sum = 0;
if (l1 != null) {
sum = l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
if (remainder != 0) {
sum += remainder;
}
if (sum > 9) {
remainder = sum / 10;
sum = sum % 10;
}
else {
remainder = 0;
}
///In here I am using tailNode has reference for adding new node to the end of Linked List
if (tailNode == null) {
l3 = new ListNode(sum);
tailNode = l3;
}
else {
tailNode.next = new ListNode(sum);
tailNode = tailNode.next;
}
}
if (remainder != 0) {
tailNode.next = new ListNode(remainder);
}
return l3;
}
}
Since I got a tail node for the end of Linked List instead of going through entire Linked List,I thought the solution 2 will have better performance.But it is still taking more time to execute than the first solution ,Any code changes would be appreciated
Solution 1 is taking 108 ms to execute while Solution 2 is taking 140 ms
