20.Add Two Numbers(两个链表的和)
Level:
Medium
题目描述:
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.
思路分析:
这道题主要考虑相加之后的进位表示,这里用flag变量进行标记,如果flag=true则代表相加有进位,进位只可能是一,这道题
应该将所有的情况都考虑全;
代码:
public class ListNode{
int val;
ListNode next;
public ListNode(int x){
val=x;
}
}
public class Solution{
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
if(l1==null&&l2==null)
return null;
if(l1==null)
return l2;
if(l2==null)
return l1;
boolean flag=false; //有进位设置为true
ListNode pNode=new ListNode(0);
ListNode res=pNode;
while(l1!=null&&l2!=null){
if(l1.val+l2.val>=10){
if(flag==true){ //有进位
pNode.next=new ListNode((l1.val+l2.val)%10+1);
}
else{
pNode.next=new ListNode((l1.val+l2.val)%10);
flag=true; //产生进位
}
}
if(l1.val+l2.val<10){
if(flag==true){ //有进位
if(l1.val+l2.val+1>=10){
pNode.next=new ListNode((l1.val+l2.val+1)%10);
}else{
pNode.next=new ListNode((l1.val+l2.val+1)%10);
flag=false;
}
}else{
pNode.next=new ListNode(l1.val+l2.val);
flag=false;
}
}
l1=l1.next;
l2=l2.next;
pNode=pNode.next;
}
while(l1!=null){
if(flag==true){//有进位
if(l1.val+1==10){
pNode.next=new ListNode(0); //不改变flag的值,保持有进位
}else{
pNode.next=new ListNode(l1.val+1);
flag=false;//没有进位
}
}
else{
pNode.next=new ListNode(l1.val);
flag=false;
}
l1=l1.next;
pNode=pNode.next;
}
while(l2!=null){
if(flag==true){
if(l2.val+1==10){
pNode.next=new ListNode(0);
}else{
pNode.next=new ListNode(l2.val+1);
flag=false;
}
}
else{
pNode.next=new ListNode(l2.val);
flag=false;
}
l2=l2.next;
pNode=pNode.next;
}
if(flag==true){ //最后如果有进位那么还行需要再产生一个节点。
pNode.next=new ListNode(1);
}
return res.next;
}
}