Article From:

Add the two numbers of the list.


 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };

class Solution {
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int c=0;
        ListNode pre=ListNode(0);
        ListNode *p=⪯
            if (l1) {c+=l1->val;l1=l1->next;}
            if (l2) {c+=l2->val;l2=l2->next;}
            p->next= new ListNode(c%10);



  At first, I think of the edge reading L1 L2 edge computing, but considering that if the two numbers are different, such as 1+111, so the read conversion into int and then converse into list, and then the test data is gone, showing that this is considered 100+111.

  It’s not a question of competition. Is it so simple?


Be careful:

  The use of the chain list.

  1. return &ans If you want to report a mistake, you must first build a starting node and then return next. Do not know why?

  2. p->next = new ListNode(x); Pay attention to this way of writing.

  3. -> . The difference is: -> the pointer to the operator of its member; is the member operator of the structure.

Link of this Article: LeetCode 2. Add Two Numbers

Leave a Reply

Your email address will not be published. Required fields are marked *