Posted on 2022-11-03 00:49
Uriel 阅读(44)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
大数加法,链表结构实现,第一个是自己的写法,多开个变量ini标记是不是第一位(要保留第一位的节点root),后一种是看到Discussion中的写法,直接多搞一个值为0的头结点,最后return头结点的next,更简洁一点点?但耗时长一点点
1 #2
2 #Runtime: 51 ms
3 #Memory Usage: 13.6 MB
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def addTwoNumbers(self, l1, l2):
12 """
13 :type l1: ListNode
14 :type l2: ListNode
15 :rtype: ListNode
16 """
17 ini = 0
18 t = 0
19 while l1 or l2 or t:
20 if l1:
21 t += l1.val
22 l1 = l1.next
23 if l2:
24 t += l2.val
25 l2 = l2.next
26 if ini == 0:
27 root = ListNode(t % 10)
28 ans = root
29 ini = 1
30 else:
31 ans.next = ListNode(t % 10)
32 ans = ans.next
33 t = t // 10
34 return root
1 #2
2 #Runtime: 80 ms
3 #Memory Usage: 13.3 MB
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def addTwoNumbers(self, l1, l2):
12 """
13 :type l1: ListNode
14 :type l2: ListNode
15 :rtype: ListNode
16 """
17 p = ListNode(0)
18 ans = p
19 t = 0
20 while l1 or l2 or t:
21 if l1:
22 t += l1.val
23 l1 = l1.next
24 if l2:
25 t += l2.val
26 l2 = l2.next
27 ans.next = ListNode(t % 10)
28 ans = ans.next
29 t = t // 10
30 return p.next