C solution (0ms) - recursive


  • 0

    We recurse to the end of the the list and add 1 to the last node.
    If the resulting sum is 10, we set the node's value to 0 and return a carry of 1.
    If the resulting sum is less than 10, there is no need to do anything further and we simply return 0.

    int plusOneHelper(struct ListNode *node) {
        if (!node) return 1;
        if (plusOneHelper(node->next) == 0) return 0;
        if (++(node->val) < 10) return 0;
        node->val = 0;
        return 1;
    }
    
    struct ListNode* plusOne(struct ListNode* head) {
        if (head == NULL || plusOneHelper(head) == 0) return head;
        struct ListNode *newHead = malloc(sizeof(struct ListNode));
        newHead->val = 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.