C++ Solution for Plus one Linked List


  • 0
    G
    class Solution {
    public:
        ListNode* plusOne(ListNode* head) {
            if(!head){head->val=1;head->next=NULL;return head;}
            vector<int> vec;
            ListNode* h=head;
            while(h){
                vec.push_back(h->val);
                h=h->next;
            }
            vec[vec.size()-1]++;
            for(int i=vec.size()-1;i>=1;i--)
                if(vec[i]>=10){vec[i]-=10;vec[i-1]++;}
    
            ListNode* result;
            ListNode* res;
            int index=0;
            if(vec[0]>=10){
                vec[0]-=10;
                vec.insert(vec.begin(),1);
                result=new ListNode(1);//
                result->next=head;
                index++;
                res=result;
                result=head;
            }
            else {
                result=head;
                res=result;
            }
    
            while(result!=NULL){
            // while(index<vec.size()){
                result->val=vec[index];
                result=result->next;
                index++;
            }
            
            return res;
        }
    };

Log in to reply
 

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