1. 程式人生 > >LeetCode: Add Two Numbers

LeetCode: Add Two Numbers

題目:

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

有兩個連結串列作為輸入,它們表示逆序的兩個非負數。如下面的兩個連結串列表示的是342和465這兩個數。你需要計算它們的和並且用同樣的方式逆序輸出。

除了0之外,兩個數首位均不為0.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

思路:

指標遍歷兩個連結串列,用一個變量表示進位,指向兩個連結串列的指標有一個為空或進位為空時終止迴圈。

程式碼:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head=new ListNode(0);
        ListNode* ptr=head;
        int carry = 0;
        while(true){
            if(l1!=NULL){
                carry+=l1->val;
                l1=l1->next;
            }
            if(l2!=NULL){
                carry+=l2->val;
                l2=l2->next;
            }
            ptr->val=carry%10;
            carry/=10;
            if(l1!=NULL||l2!=NULL||carry!=0){
                ptr=(ptr->next=new ListNode(0));
            }
            else
            break; 
        }
        return head;
    }
};