Leetcode add-two-numbers

来源:互联网 发布:淘宝自粘墙纸有甲醛吗 编辑:程序博客网 时间:2024/06/17 02:53
 //Reference: http://www.programcreek.com/2012/12/add-two-numbers/
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } *//*题意是将两个链表相加 但这两个链表是反序存储的 (每个节点只包含一位数字)要求返回相加后的链表 大于10 要进位 还是保留1位数字注意 Input  5    5 Output [0,1]*/class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1==null)//如果        return l2;        if(l2==null)        return l1;        int carry=0;        ListNode newHead=new ListNode(-1);        ListNode l3=newHead;        while(l1!=null||l2!=null){        if(l1!=null){        carry+=l1.val;        l1=l1.next;        }        if(l2!=null){        carry+=l2.val;        l2=l2.next;        }        l3.next=new ListNode(carry%10);        carry=carry/10;        l3=l3.next;        }        if(carry==1)//如果carry/10=1 如5+5 则结果为 0 ,1        l3.next=new ListNode(1);        return newHead.next;    }}

原创粉丝点击