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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3=new ListNode(0); //调用构造函数
int flag=0; //定义进位符
ListNode p1=l1,p2=l2,p3=l3;
while(p1!=null || p2!=null){
if(p1!=null){
flag+=p1.val;
p1=p1.next;
}
if(p2!=null){
flag+=p2.val;
p2=p2.next;
}
p3.next=new ListNode(flag%10); //注意这儿的书写
p3=p3.next;
flag/=10;
}
if(flag!=0) p3.next=new ListNode(1); //如果进位不为0,则后边加1
return l3.next; //根据前边的逻辑,l3的第一个节点无用所以弃用,因为置为了0
}
}
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3=new ListNode(0);
int flag=0;
ListNode p1=l1,p2=l2,p3=l3;
while(p1!=null || p2!=null){
if(p1!=null){
flag+=p1.val;
p1=p1.next;
}
if(p2!=null){
flag+=p2.val;
p2=p2.next;
}
p3.val=flag%10; //不同于上边的是,这儿没有把第一个节点给废弃掉
flag/=10;
if(p1!=null || p2!=null) //如果后续还有加操作,才创建新节点p3.next。否则不创建
p3=(p3.next=new ListNode(0));
}
if(flag!=0) p3.next=new ListNode(1); //如果进位为1,则创建一个val为1的新节点
return l3;
}
}