c++ using iterative method


  • 0
    C

    I have seen that the most significant digit is at the end of the list, that is easier. For this problem, an iterative method, which has "reverse" concept naturally, can be worked out.
    '''
    int calCarray(ListNode* head){
    if (!head) return 1;
    int tmp=head->val+calCarray(head->next);
    head->val=tmp%10;
    return tmp/10;
    }
    ListNode* plusOne(ListNode* head) {
    if (!head) return NULL;
    int carray=calCarray(head);
    if (carray==0) return head;
    ListNode* newHead=new ListNode(1);
    newHead->next=head;
    return newHead;
    }
    '''


Log in to reply
 

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