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.
这个题目有点像LeetCode的415题字符串相加那题,不过这题是基于链表的所以得循环一下求得这个数的长度不像字符串那么方便
其他的话基本是一样的
solution
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = null; //定义根结点
ListNode tail = null; //定义尾结点
int jin = 0; //进位标志
ListNode a = l1;
ListNode b = l2;
int lena = 1;
int lenb = 1;
while(a.next!=null){ //求l1的节点数注意不能直接用l1否则后面l1就不是头结点了
lena ++;
a = a.next;
}
while(b.next!=null){ //求l2的节点数
lenb ++;
b = b.next;
}
while(lena>=0||lenb>=0){ //循环相加
int i1,i2;
if(l1 == null)i1=0; //这里有个技巧因为我们不判断l1和l2谁长所以如果谁是空了加0就好
else i1=l1.val;
if(l2 == null)i2=0;
else i2=l2.val;
if(l1==null&&l2==null){ //如果l1和l2都是空了那很显然这个运算已经结束了break出去
if(jin==1) //这里注意如果l1和l2都空了但是进位标志为1那么tail后面还要插入一个值为1的结点
tail.next = new ListNode(1);
break;
}
int n = i1 + i2 +jin;
if(jin==1)
jin=0;
if(n>=10){
n-=10;
jin+=1;
}
if(root==null){
ListNode t = new ListNode(n);
root = t;
tail = t;
}
else{
ListNode t = new ListNode(n);
tail.next = t;
tail = tail.next;
}
if(l1 != null)l1 = l1.next; //l1和l2往后一个结点如果其等于空就不需要操作了
if(l2 != null)l2 = l2.next;
lena--; //l1的长度和l2的长度作为判断条件循环一次后各减去1
lenb--;
}
return root;
}
}