java ListNode链表求和

题目

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

样例

给出两个链表3->1->5->null 和 5->9->2->null,返回8->0->8->null
分析

package leetcode;

class ListNode{
    int val;
    ListNode nextNode;
    ListNode(int val){
        this.val=val;
        this.nextNode=null;
    }
}
public class n5ListNodePlus {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a=new int[]{1,5,6};
        int[] b=new int[]{4,8,2};
        ListNode alist=buildListNode( a);
        ListNode blist=buildListNode( b);
        ListNode listNode;


        listNode=alist;
        while(listNode!=null){          
            System.out.print(listNode.val);
            listNode=listNode.nextNode;
        }
        System.out.println();
        listNode=blist;
        while(listNode!=null){      
            System.out.print(listNode.val);
            listNode=listNode.nextNode;
        }
        System.out.println();
        listNode=addList(alist,blist);
        while(listNode!=null){      
            System.out.print(listNode.val);
            listNode=listNode.nextNode;
        }

    }
    public static ListNode addList(ListNode list1,ListNode list2){
        ListNode pre=null;
        ListNode last=null,newNode=null;
        ListNode result=null;
        int val=0;
        int carry=0;
        while(list1!=null||list2!=null){
            val=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)%10;
            carry=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)/10;
            list1=list1==null?null:list1.nextNode;
            list2=list2==null?null:list2.nextNode;  
            newNode=new ListNode(val);
            if(pre==null){
                pre=newNode;
                last=newNode;
            }else{
                last.nextNode=newNode;
                last=newNode;
            }

        }
        if(carry>0){
            newNode=new ListNode(carry);
            last.nextNode=newNode;
            last=newNode;
        }
        return pre;

    }
    public static ListNode buildListNode(int [] list){
        ListNode first=null,last=null,newNode;
        for(int i=0;i<list.length;i++){
            newNode=new ListNode(list[i]);
            if(first==null){
                first=newNode;
                last=newNode;
            }else{
                last.nextNode=newNode;
                last=newNode;
            }
        }
        return first;
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值