LeetCode 2. Add Two Numbers

来源:互联网 发布:淘宝客拍a发b从哪找 编辑:程序博客网 时间:2024/05/21 06:23

题目描述

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

题目解析

循环ListNode newNode(val%10),我以为会新建一个newNode,但并不知,只是在循环同一个节点
应当使用ans->next = new ListNode(val%10)
要考虑两个数不等长,以及可能会增加一位。
第一次的代码有点啰嗦
看了别人的代码试着改了下自己的。

第一次AC代码

/** * 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 add1 = 0,val1,val2,val;        ListNode*ans = NULL,*ansLast = NULL;        while(l1!=NULL||l2!=NULL)        {            if(l1!=NULL)            {                val1 = l1->val;                l1 = l1->next;            }            else            {                val1 = 0;            }            if(l2!=NULL)            {                val2 = l2->val;                l2 = l2->next;            }            else            {                val2 = 0;            }            val = val1 + val2 + add1;            if(val>9)            {                add1 = 1;            }            else            {                add1 = 0;            }            if(ans==NULL)            {                ans = new ListNode(val%10);                ansLast = ans;            }            else            {                ansLast->next = new ListNode(val%10);                ansLast = ansLast->next;            }        }        if(add1==1)        {            ansLast->next = new ListNode(1);        }        return ans;    }};

修改后代码

参考 @LHearen很简洁的代码

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)     {        int carry;        ListNode newNode(0);        ListNode *ansLast=&newNode;        while(l1||l2||carry)        {            carry += (l1 ? l1->val : 0) + (l2 ? l2->val : 0);            ansLast->next = new ListNode(carry%10);            ansLast = ansLast->next;            carry /= 10;            if(l1)            {                l1 = l1->next;            }            if(l2)            {                l2 = l2->next;            }        }        return newNode.next;    }
0 0