Leetcode 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

思路: 题目给的正向List无法处理最后一个node加一后的进位问题。所以思路是将List reverse过来,加一,然后在reverse一次。

注意L12到L14,这里需要将node.val先存一下,否则L13会将这个值破坏,导致node.val = 9时变得carry本应是1,结果输出0。

 1 class Solution(object):
 2     def plusOne(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: ListNode
 6         """
 7         end = self.reverseList(head)
 8         carry = 1
 9         start = end
10         prev = ListNode(0)
11         while start:
12             cur = start.val
13             start.val = (cur + carry)%10
14             carry = (cur + carry)//10
15             
16             prev = start
17             start = start.next
18         
19         if carry == 1:
20             prev.next = ListNode(1)
21         
22         return self.reverseList(end)     
23         
24             
25     
26     def reverseList(self, head):
27         prev = None
28         
29         while head:
30             temp = head.next
31             head.next = prev
32             prev = head
33             head = temp
34         
35         return prev

 

posted @ 2017-01-23 14:26  lettuan  阅读(185)  评论(0编辑  收藏  举报