您的位置:首页 > 其它

链表——将两个链表上的数字相加(考虑进位)并将和放入新链表

2016-05-09 19:47 357 查看
题目:

给予两个链表,每个节点中有一个0-9的数字,将相应位置上的数字相加并进位,用新的链表存储其和。

例如:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路:

可能的情况有:

1.两个链表first和second都没有到表尾;

2.一个到表尾,另一个没有;

3.两个都到表尾;

注意!当一个链表到结尾或者两个链表都到结尾时,但是carry不为0,程序仍不能结束;

 public ListNode addTwoNumbers(ListNode first, ListNode second) {
        if(first==null)
            return second;
        if(second==null)
            return first;
        
        int sum=0;//first和second对应结点的和,值为(0-9);
        int carry=0;//first和second对应结点求和后对应的进位,值为(0或1);
        
        ListNode head=new ListNode(0);
        ListNode cur=head;

        while(first != null||second != null||carry != 0)
            {
            int num1=0;
            int num2=0;
            
            if(first!=null)
                {
                num1=first.val;
                first=first.next;
            }
            if(second!=null)
                {
                num2=second.val;
                second=second.next;
            }
            sum=(carry+num1+num2)%10;
            ListNode temp=new ListNode(sum);
            cur.next=temp;
            cur=cur.next;
            
            carry=(carry+num1+num2)/10;    
        }
        return head.next;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: