You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Line 25: cannot find symbol: variable value
Line 92: missing return statement
Showing the first failed test case.
input | output | expected | |
---|---|---|---|
{5}, {5} | {0} | {0,1} |
|
Program Runtime: 540 milli secs
Program Runtime: 1184 milli secs
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
int plus = 0;
ListNode result = null;
ListNode preNode = null;
ListNode p1 = l1;
ListNode p2 = l2;
while (p1 != null) {
int tmp = p1.val;
p1 = p1.next;
if (p2 != null) {
tmp = tmp + p2.val + plus;
p2 = p2.next;
if (tmp >= 10) {
plus = 1;
tmp = tmp - 10;
}
else {
plus = 0;
}
}
else {
tmp = tmp + plus;
if (tmp >= 10) {
plus = 1;
tmp = tmp - 10;
}
else {
plus = 0;
}
}
if (result != null) {
ListNode node = new ListNode(tmp);
if (preNode != null) {
preNode.next = node;
preNode = node;
}
}
else {
result = new ListNode(tmp);
preNode = result;
}
}
while (p2 != null) {
int tmp = p2.val + plus;
p2 = p2.next;
if (tmp >= 10) {
plus = 1;
tmp = tmp - 10;
}
else {
plus = 0;
}
if (result != null) {
ListNode node = new ListNode(tmp);
if (preNode != null) {
preNode.next = node;
preNode = node;
}
}
else {
result = new ListNode(tmp);
preNode = result;
}
}
if (plus == 1) {
ListNode node = new ListNode(plus);
if (preNode != null) {
preNode.next = node;
preNode = node;
}
}
return result;
}
}