题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个链表,从头到尾就是从大到小表示一个数字的位,现在要把这个数字乘 2,求最终的数字链表。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head):
pre = None
while head:
nxt = head.next
head.next = pre
pre = head
head = nxt
return pre

def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
head = self.reverseList(head)
cur = head
add_nxt = 0
while cur:
cur.val *= 2
cur.val += add_nxt
add_nxt = 0
if cur.val >= 10:
add_nxt = 1
cur.val -= 10

if not cur.next:
break
cur = cur.next

if add_nxt > 0:
cur.next = ListNode(1)

return self.reverseList(head)