• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

leetcode刷题2

开发技术 开发技术 1周前 (04-07) 3次浏览
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Linklist(object):
def __init__(self):
self._head = None

list1 = [2, 4, 5, 9]
list2 = [5, 6, 4]

n1 = ListNode()
n2 = ListNode()
temp1 = n1
temp2 = n2
for i in range(len(list1)): #建立了以n1为起始节点的链表n1
if i == 0:
n1.val = list1[0]
else:
temp1.next = ListNode(list1[i])
temp1 = temp1.next

for j in range(len(list2)): #以n2为起始点的链表n2
if j == 0:
n2.val = list2[0]
else:
temp2.next = ListNode(list2[j])
temp2 = temp2.next

class Solution(object):
def addTwoNumbers(self, l1:ListNode, l2:ListNode) -> ListNode:
flag = 0
next_sum = 0
res = ListNode()
temp = res
size3 = 0
while l1 != None and l2 != None:
if flag == 0:
p = l1.val + l2.val
res.val = p % 10
next_sum = int(p/10)
flag += 1
else:
p = l1.val + l2.val + next_sum
next_sum = int(p/10)
temp.next = ListNode(p%10)
temp = temp.next
l1 = l1.next
l2 = l2.next
size3 += 1
while l1:
p = l1.val + next_sum
next_sum = int(p/10)
temp.next = ListNode(p%10)
temp = temp.next
l1 = l1.next
size3 += 1
while l2:
p = l2.val + next_sum
next_sum = int(p/10)
temp.next = ListNode(p%10)
temp = temp.next
l2 = l2.next
size3 += 1
if next_sum != 0:
temp.next = ListNode(next_sum)
size3 += 1
return res, size3



s = Solution()
n3, size3 = s.addTwoNumbers(n1, n2)

for i in range(size3):
print(n3.val)
n3 = n3.next

程序员灯塔
转载请注明原文链接:leetcode刷题2
喜欢 (0)