问题描述
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.
AC代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp = new ListNode(0);
ListNode head = tmp;
int carry = 0;
int val = 0;
while(l1 != null || l2 != null){ //即使 l1 和 l2 长度不一致也适用,极大地减少了代码量
if(l1 == null) l1 = new ListNode(0); // 如果 l1 已经遍历完了,l1 的下一个节点用 0 代替
if(l2 == null) l2 = new ListNode(0); //同理
val = l1.val + l2.val + carry; // 别忘了加进位
carry = val / 10;
tmp.next = new ListNode(val % 10);
tmp = tmp.next;
l1 = l1.next;
l2 = l2.next;
}
if(carry != 0) tmp.next = new ListNode(carry); //别忘记了:最后如果有进位的话,要把进位加上
return head.next;
}
}