C++_Time: O(n), Space: O(1)


  • 0

    This problem sucks...

    class Solution {
    public:
    ListNode* plusOne(ListNode* head) {
        //if(head == nullptr){head->val = 1; return head;}
        ListNode* ptr = head;
        ListNode* pre = nullptr;
        
        while(ptr != nullptr){
            if(ptr->val < 9){pre = ptr;}
            ptr = ptr->next;
        }
        
        if(pre != nullptr){
            pre->val = pre->val + 1;
            ptr = pre->next;
        }else{
            head->val = 1;
            ListNode* dummy = new ListNode(0);
            dummy->next = head->next;
            head->next = dummy;
            ptr = head->next;
        }
        
        while(ptr){
            ptr->val = 0;
            ptr = ptr->next;
        }
        
        return head;
    }
    };

Log in to reply
 

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