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
http://blog.youkuaiyun.com/linhuanmars/article/details/19957829
【3.处理两个linked list的问题,循环的条件一般为 while( l1 && l2 )
,再处理剩下非NULL
的list。】
题目:617+295=912,那么reverse-order用链表表示为 7->1->6 + 5->9->2 = 2->1->9 ,既912。
思路:1.从产生新list考虑,因为是insertLast,那么新list需要head,pre;进行加法操作,还需要digit和carry。
2.三个循环,均是先计算digit和carry,然后构造新节点,insertLast,注意head是否为null,要分case讨论,最后更新pre(既tail指针)。
3.trick是最后的if判断carry是否为1。
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=null;//【注意1】
ListNode pre=null; //【注意1】
int digit=0;
int carry=0;
while(l1!=null && l2!=null){
digit=(l1.val+l2.val+carry)%10;
carry=(l1.val+l2.val+carry)/10;
ListNode newNode=new ListNode(digit);
if(head==null)
head=newNode;
else
pre.next=newNode;
pre=newNode;
l1=l1.next;
l2=l2.next;
//n1==null or n2==null, break;
}
while(l1!=null){
digit=(l1.val+carry)%10;
carry=(l1.val+carry)/10;
ListNode newNode=new ListNode(digit);
if(head==null)
head=newNode;
else
pre.next=newNode;
pre=newNode;
l1=l1.next;
//l1==null , break;
}
while(l2!=null){
digit=(l2.val+carry)%10;
carry=(l2.val+carry)/10;
ListNode newNode=new ListNode(digit);
if(head==null)
head=newNode;
else
pre.next=newNode;
pre=newNode;
l2=l2.next;
//l2==null , break;
}
if(carry>0){
ListNode newNode=new ListNode(1);
pre.next=newNode;//【注意2】
}
return head;
}
}
【注意1】不赋初值,编译出错。
【注意2】carry大于0,那么head一定非空。
【注意3】smilence:“3.处理两个linked list的问题,循环的条件一般为 while( l1 && l2 ) ,再处理剩下非NULL 的list。”
循环条件分析:对每一个节点都进行操作。不如像上面的code,写上break循环条件,这样清楚一点。