C++ solution, each time delete a tailor node


  • 0
    G

    '''
    class Solution {
    public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    ListNode** p1=&l1, *p2 = &l2;
    int carry = 0;
    ListNode
    header = NULL;
    while((*p1) || (*p2) || carry)
    {
    while(*p1 && (*p1)->next!=NULL) p1=&(*p1)->next;
    while(*p2 && (*p2)->next!=NULL) p2=&(*p2)->next;
    int t1=0, t2=0;
    if(*p1) t1=(*p1)->val;
    if(p2) t2=(p2)->val;
    int result = t1 + t2 + carry;
    carry = result/10;
    ListNode
    node = new ListNode(result%10);
    if(header == NULL)
    header = node;
    else{
    ListNode
    tmp = header;
    header = node;
    node->next = tmp;
    }
    if(*p1) *p1=(*p1)->next;
    if(*p2) *p2 =(*p2)->next;
    p1=&l1;
    p2=&l2;
    }
    return header;
    }
    };

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.