Total Accepted: 120829
Total Submissions: 544194
Difficulty: Medium
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
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
以链表的形式存储两个十进制数,计算两数和。需要运用后插法构建结果的链表。
我的AC代码如下
public class AddTwoNumbers {
public static void main(String[] args) {
addTwoNumbers(new ListNode(5), new ListNode(5));
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode head = new ListNode(0);
ListNode pre = head;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int sum = 0;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
sum += carry;
carry = sum / 10;
ListNode cur = new ListNode(sum % 10);
pre.next = cur;
pre = cur;
}
return head.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}