O(1) Extra Space Solution : Reverse & Reverse


  • 0
    F
    class Solution {
    public:
        ListNode* plusOne(ListNode* head) {
            ListNode * pre = nullptr;
            while(head)
            {
                auto next = head->next;
                head->next = pre;
                pre = head;
                head = next;
            }
            swap(head, pre);
            int carry = 1;
            while(head)
            {
                int sum = head->val + carry;
                head->val = sum%10;
                carry = sum/10;
                auto next =head->next;
                head->next = pre;
                pre = head;
                head = next;
            }
            head = pre;
            if (carry > 0)
            {
                auto temp = new ListNode (carry);
                temp->next = head;
                head = temp;
            }
            return head;
        }
    };
    

Log in to reply
 

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