[Leetcode] ADD Numbers

Source: Internet
Author: User

Test instructions: the addition of large number of linked list, but the number on the list is reversed.

Source: https://leetcode.com/problems/add-two-numbers/

Analysis:

1. If the linked list is empty, no calculation is necessary; If all two linked lists are empty, the return is empty (the list is not cooked).

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: OneListNode *addtwonumbers (ListNode *l1, ListNode *L2) { A         if(L1==null)returnL2; -         if(L2==null)returnL1; -          the         intcarry =0; -listnode* tail =NewListNode (0); -listnode* ptr =tail; -          +          while(L1! = NULL | | L2! =NULL) { -             intVal1 =0; +             if(L1! =NULL) { AVal1 = l1->Val; atL1 = l1->Next; -             } -              -             intVal2 =0; -             if(L2! =NULL) { -Val2 = l2->Val; inL2 = l2->Next; -             } to              +             intTMP = val1 + Val2 +carry; -Ptr->next =NewListNode (tmp%Ten); thecarry = tmp/Ten; *PTR = ptr->Next; $         }Panax Notoginseng         if(Carry = =1) Ptr->next =NewListNode (1); -         returnTail->Next; the     } +};

[Leetcode] ADD Numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.