369. Plus One Linked List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* plusOne(ListNode* head) {
        if (helper(head)) {
            ListNode* newHead = new ListNode(1);
            newHead->next = head;
            head = newHead;
        }
        return head;
    }
private:
    int helper(ListNode* head) {
        if (!head) return 1;
        head->val += helper(head->next);
        if (head->val == 10) {
            head->val = 0;
            return 1;
        }
        return 0;
    }
};

results matching ""

    No results matching ""