LeetCode2.2.1 @ Add Two Numbers D3F4

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.csdn.net/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循环条件,这样清楚一点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值