用一个 非空 单链表来表示一个非负整数,然后将这个整数加一。
你可以假设这个整数除了 0 本身,没有任何前导的 0。
这个整数的各个数位按照 高位在链表头部、低位在链表尾部 的顺序排列。
示例:
输入: [1,2,3]
输出: [1,2,4]
思路1:
直接转为十进制整数,加一
然后新建链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
summ = 0
while head:
summ = summ*10+head.val
head = head.next
summ+=1
summ = str(summ)
h = ListNode(int(summ[0]))
ans = h
l = len(summ)
for i in range(1,l):
h.next = ListNode(int(summ[i]))
h = h.next
return ans
思路2:
哨兵头节点
加法运算
找出最靠右的不是 9 的数字,将该数字加 1。然后将该数字之后所有的 9 改成 0。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
h = head
ee = ListNode()
while h:
if h.next==None:
ee = h
h = h.next
if ee.val !=9:
ee.val +=1
else:
h = head
ee = ListNode(-1)
while h:
if h.val!=9:
ee = h
h = h.next
if ee.val == -1:
ee.val=1
ee.next=head
while head:
head.val=0
head = head.next
return ee
ee.val+=1
ee = ee.next
while ee:
ee.val=0
ee = ee.next
return head