Add Two Numbers

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

  遍历两个链表,对每个节点依次相加即可,最后遍历完两个链表之后还要注意进位的值是否为0.

  c++实现:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode *head = NULL,*p = NULL;
        while(l1||l2){
            if(l1){
                carry += l1->val;
                ListNode *temp = l1;
                l1 = l1->next;
                free(temp);
            }
            if(l2){
                carry += l2->val;
                ListNode *temp = l2;
                l2 = l2->next;
                free(temp);
            }
            ListNode *temp = new ListNode(carry%10);
            carry /= 10;
            if(p){
                p->next = temp;
                p = p->next;
            }
            else{
                head = p = temp;
            }
        }
        if(carry){
            p->next = new ListNode(carry);
        }
        return head;
    }

  java实现:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ret = null;
        ListNode p = null;
        int carry = 0;
        while(l1!=null||l2!=null){
            int x = 0,y = 0,sum = 0;
            if(l1!=null){
                x = l1.val;
                l1 = l1.next;
            }
            if(l2!=null){
                y = l2.val;
                l2 = l2.next;
            }
            sum = x+y+carry;
            carry = sum/10;
            ListNode temp = new ListNode(sum%10);
            if(ret==null){
                ret = temp;
                p = ret;
            }
            else{
                p.next = temp;
                p = p.next;
            }
        }
        if(carry>0){
            p.next = new ListNode(carry);
        }
        return ret;
    }

 

posted on 2015-10-03 22:57  louwqtc  阅读(140)  评论(0编辑  收藏  举报

导航