3ms C++ ez iterative


  • 0
    M
    ListNode* plusOne(ListNode* head) {
            if(!head)return new ListNode(1);
            ListNode *nhead=reverse(head);
            int carry=1;
            ListNode* temp=nhead;
            while(temp){
                int num= temp->val+carry;
                temp->val= num%10; 
                carry= num/10;
                if(!carry) break;
                temp=temp->next;
            }
            if(carry)head->next= new ListNode(1); //previous head becomes current tail
            head=reverse(nhead);
            return head;
        }
        
        ListNode* reverse(ListNode* head){
            if(!head ||!head->next)return head;
            ListNode* tail=head, *cur=head->next;
            while(cur){
                tail->next=cur->next;
                cur->next=head;
                head=cur;
                cur=tail->next;
            }
            return head;
        }

Log in to reply
 

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