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;
    }
};
posted @ 2019-03-20 17:08  isLiuhy  阅读(192)  评论(0编辑  收藏  举报