369 Plus One Linked List

Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Input:
1->2->3

Output:
1->2->4

The Idea: A recursive solution to this is natural because we get a natural stack in the process. First iterate to the end. Then if the number is 9, then we know it must increment the next available base, so set it to 0. Otherwise if the number isn't 9, then we just increment the number and finish there with a flag. The final edge case to consider is when we finish iteration but no flag was triggered. This means value was zeroed out, and we must add a newListNode(1) as the new head.

Complexity: O(N) time and space

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    stop = False
    def plusOne(self, head):
        self.__plusOne(head)
        if self.stop is False:
            newHead = ListNode(1)
            newHead.next = head
            return newHead
        else:
            return head

    def __plusOne(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if head is not None:
            self.plusOne(head.next)
            if head.val == 9 and self.stop is False:
                head.val = 0
            elif head.val != 9 and self.stop is False:
                head.val += 1
                self.stop = True

Last updated