1. 程式人生 > >【LeetCode 002】Add Two Numbers

【LeetCode 002】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.
題意:給出兩個儲存數字的單向非空連結串列,求它們的和連結串列。

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:依次求解即可。兩個需要注意的地方:一,兩個連結串列不等長,這時候若其中一個連結串列加完,則後面都是0. 這可以每一步都判斷; 二,加法進位,連結串列加完後需要檢查進位是否為0,否則需要單獨再加一個結點。

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int sum=0,carry=0;
        ListNode* head=new ListNode(0),* tmp=head;
        while(l1||l2||carry){
            int sum=(l1?l1->val:0)+(l2?l2->val:0)+carry;         
            carry=sum/10;
            tmp->next=new ListNode(sum%10);
            tmp=tmp->next;
            l1=l1?l1->next:nullptr;
            l2=l2?l2->next:nullptr;
        }
        return head->next;
    }
C++中,指標可以是否為空可以直接當做bool型來判斷,所以
            (l1->next!=nullptr)||(l2->next!=nullptr)||c!=0 
可以簡化成:  l1||l2||c