LeetCode002 ADD Numbers C language

Source: Internet
Author: User

You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list. Input: (2, 4, 3) + (5, 6, 4) output:7, 0, 8Subscribe to see which companies asked this quest Ion

Test instructions: It is actually 342+465=807 and then the reverse output. "It was not clear at first. 】

Refer to others. At first Test instructions didn't understand ...

/** * definition for singly-linked list. * struct listnode {  *     int val; *     struct listnode  *next; * }; */struct listnode* addtwonumbers (STRUCT LISTNODE* L1,  STRUCT LISTNODE* L2)  {    struct ListNode *l3 =  ( struct listnode *) malloc (sizeof (Struct listnode));    l3->val=0;     l3->next=null;    //this side because L3 is always backward, so return to the head to add a head to indicate.     struct listnode* head = l3;    l3->val=l1- >val+l2->val;    //while cycle to determine whether to apply for a new node     l1=l1->next;     l2=l2->next;    while (l1| | l2| | l3->val>9) {        l3->next= (Struct listnode *) malloc (sizeof (Struct listnode));         l3->next->val=0;        l3->next->next=null;         if (L1) {             l3->next->val+=l1->val;             l1=l1->next;        }         if (L2) {            l3->next->val+=l2- >val;            l2=l2->next;         }        if (l3->val>9) {             l3->next->val+=l3->val/10;             l3->val=l3->val%10;         }        l3=l3->next;    }     return head;}

PS: Mainly to make clear there are several cases. 9+8 this need to apply for nodes; 12+9 this unequal length;

Note the use of the C-language linked list ...

LeetCode002 ADD Numbers C language

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.