题目: Add Two Numbers
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.
翻译:
给定两个非空链表,表示两个非负整数。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将这两个数字相加并以链表的形式返回。
您可以假设这两个数字不包含任何前导零,除了数字0本身。
思路:两个链表的数字相反存储,也就是我们从头结点相加时是从个位开始的,那么每次我们计算时,只计算本位和低位的进位,将本次产生的进位留给下次计算;注意,两个链表的长度可能是不相等的;
/**
* 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) {
//判断只有一个链表的情况
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode head=new ListNode(-1);// 头节点
ListNode cur=head;//尾节点
int n1=0; //本位
int n2=0; //进位
while(l1!=null || l2!=null){
if(l1!=null&&l2!=null){ //两个链表都不为空
n1=l1.val+l2.val+n2;
l1=l1.next;
l2=l2.next;
}else if(l1!=null){ //只有一个链表有数据
n1=l1.val+n2;
l1=l1.next;
}else if(l2!=null){
n1=l2.val+n2;
l2=l2.next;
}
cur.next=new ListNode(n1%10); //创建本位链表
cur=cur.next;
n2=n1>9 ? 1 : 0; //判断是否有进位
}
if(n2!=0){ //判断最后的进位是否有值
cur.next=new ListNode(1);
}
return head.next;
}
}