2. 兩數相加

坑點


  • 若是最後有進位,要多加一個節點1。好比5,5的結果是0->1
  • 多注意空指針問題

收穫


  • 經過指針訪問鏈表節點的元素要用->,而不是用.
  • 熟悉了鏈表的操做

代碼


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
        int ford = 0;
        ListNode * ans = new ListNode(0);
        ListNode * tail = ans;
        while(l1 != NULL || l2 != NULL)
        {
            int num1 = 0;
            int num2 = 0;
            int temp = 0;
            if(l1 != NULL)
            {
                num1 = l1->val;
            }
            if(l2 != NULL)
            {
                num2 = l2->val;
            }
            temp = num1 + num2 + ford;
            if(temp >= 10)
            {
                temp = temp % 10;
                ford = 1;
            }
            else
            {
                ford = 0;
            }
            ListNode * pthis = new ListNode(temp);
            tail->next = pthis;
            tail = pthis;
            if(l1 != NULL)
            l1 = l1->next;
            if(l2 != NULL)
            l2 = l2->next;
        }
        if(ford == 1)
        {
            ListNode * pthis = new ListNode(1);
            tail->next = pthis;
            tail = pthis;
        }
        return ans->next;
    }
};
相關文章
相關標籤/搜索