首页 > 代码库 > Leetcode 369. Plue one Linked List
Leetcode 369. Plue 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
Leetcode 369. Plue one Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。