Simple solution using reserve link list helper - 3ms


  • 0
    D
    class Solution {
    private:
        ListNode* reverseNode(ListNode* head) {
            ListNode* tmp;
           ListNode* prev = NULL;
           while(head->next != NULL){
               tmp = head->next; 
               head->next = prev;
               prev = head;
               head = tmp;
           }
           head->next = prev;
           return head;
        }
    public:
        ListNode* plusOne(ListNode* head) {
            if(!head) return head;
            ListNode* root = reverseNode(head);
            ListNode* tmp = root;
            tmp->val = tmp->val+1;
            if (tmp->val == 10) {
                tmp->val = 0;
                while(tmp->next){
                    tmp = tmp->next;
                    tmp->val = tmp->val+1;
                    if (tmp->val<10) break;
                    tmp->val = 0;
                }
                if (tmp->val == 0){
                    tmp->next = new ListNode(1);
                }
            }
            return reverseNode(root);
        }
    };
    

Log in to reply
 

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