369.Plus One Linked List

Tags: [list], [linked_list], [reverse]

Com: {g}

Hard: [#]

Link: https://leetcode.com/problems/plus-one-linked-list/\#/description

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

Solution: Reverse

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

class Solution(object):
    def plusOne(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            raise ValueError('the input is invalid')

        head = self.reverse(head)
        curr = head
        prev = None
        carry = 1
        while curr:
            tmp = curr.val + carry
            curr.val = tmp % 10
            carry = tmp / 10

            prev = curr
            curr = curr.next

        if carry > 0:
            prev.next = ListNode(carry)

        return self.reverse(head)

    def reverse(self, head):
        if not head or not head.next:
            return head

        prev = None
        curr = head
        next = None
        while curr:
            next = curr.next
            curr.next = prev
            prev = curr
            curr = next

        return prev

Note:

  • Time complexity = O(n), n is the length of the given linked list.

results matching ""

    No results matching ""