[程序员面试金典]-链式A+B

题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
思路:只要链表还有未处理的节点,或者还有进位(即进位不为0),就进行节点的相加;对于当前指针只想空节点时,使用0代表其值,并且使用null代表下一轮迭代节点。

package niuke;

public class AddList {
    public ListNode addList(ListNode A,ListNode B){
        ListNode iter1=A,iter2=B;
        ListNode list=null,tail=null;
        int carry=0;
        while(iter1!=null||iter2!=null||carry!=0){
            int num1=iter1==null?0:iter1.val;
            int num2=iter2==null?0:iter2.val;

            int sum=num1+num2+carry;
            carry=sum/10;
            sum=sum%10;
            if(list==null){
                list=new ListNode(sum);
                tail=list;
            }else{
                tail.next=new ListNode(sum);
                tail=tail.next;
            }

            iter1=iter1==null?null:iter1.next;
            iter2=iter2==null?null:iter2.next;
        }
        return list;

    }
    public void showNode(ListNode pHead){
        if(pHead==null) return;
        int count=0;
        while(pHead!=null){
            System.out.println("第"+count+"次:"+pHead.val);
            pHead=pHead.next;
            count++;
        }
    }

    public static void main(String[] args) {
        ListNode head=new ListNode(1);
        ListNode head1=new ListNode(5);
        ListNode head2=new ListNode(4);     


        ListNode head3=new ListNode(2);
        ListNode head4=new ListNode(6);
        ListNode head5=new ListNode(7);

        head.next =head1;
        head1.next=head2;
        //head2.next=null;

        head3.next=head4;
        head4.next=head5;
        //head5.next=null;
        //System.out.println("shuchu");
        AddList pt=new AddList();
        ListNode addNode=pt.addList(head, head3);   
        pt.showNode(addNode);   
    }
}

结果分析:
第一个链表为1->5->4,即451;
第二个链表为2->6->7,即762;
相加的结果为1213。

第0次:3
第1次:1
第2次:2
第3次:1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值