Clean c++ solution


  • 0
    1. create a dummy node with value 0 followed by current head;
    2. Find the last one that is not 9;
    3. Increase the found by one and update all following 9s to 0s;
    ListNode* plusOne(ListNode* head) {
            ListNode *dummy = new ListNode(0);
            dummy->next = head;
            head = dummy;
            ListNode *toIncrease = dummy;
            while (head->next) {
                if (head->next->val != 9) {
                    toIncrease = head->next;
                }
                head = head->next;
            }
            toIncrease->val += 1;
            while (toIncrease->next) {
                toIncrease->next->val = 0;
                toIncrease = toIncrease->next;
            }
            if (dummy->val == 1) {
                head = dummy;
            } else {
                head = dummy->next;
                delete dummy;
            }
            return head;
    }
    

Log in to reply
 

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