题目:
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
做了445(https://blog.csdn.net/qq_37333947/article/details/108907210)以后这道题完全无难度了,刚开始没仔细看题就按445的写了,没想到这道题是直接让你从head开始相加往后进位,害,搞得我刚开始还写了stack,其实只需要无脑顺序遍历然后新建一个result无脑往后加就行了。
Runtime: 2 ms, faster than 67.54% of Java online submissions for Add Two Numbers.
Memory Usage: 39.5 MB, less than 18.52% of Java online submissions for Add Two Numbers.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode();
ListNode curr = dummyHead;
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;
int value = sum % 10;
carry = sum / 10;
ListNode newNode = new ListNode(value);
curr.next = newNode;
curr = newNode;
}
return dummyHead.next;
}
}