Python stack solution


  • 0
    T
    class Solution(object):
        def plusOne(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            
            stack = []
            node = head
            while node:
                stack.append(node)
                node = node.next
            
            carry = 1
            while stack:
                node = stack.pop()
                
                if node.val == 9 and carry:
                    node.val = 0
                else:
                    node.val += carry
                    carry = 0
                    break
            
            if carry:
                node = ListNode(1)
                node.next = head
            else:
                node = head
            
            return node
    

    Push every node onto a stack, then carry the one as long as we need to.


Log in to reply
 

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