-
Notifications
You must be signed in to change notification settings - Fork 481
/
0445.py
75 lines (64 loc) · 1.69 KB
/
0445.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
stack_list1, stack_list2, stack_list3 = list(), list(), list()
h = ListNode(-1)
cur = h
while l1 != None:
stack_list1.append(l1.val)
l1 = l1.next
while l2 != None:
stack_list2.append(l2.val)
l2 = l2.next
add = 0
while stack_list1 or stack_list2 or add:
if stack_list1:
top1 = stack_list1.pop()
else:
top1 = 0
if stack_list2:
top2 = stack_list2.pop()
else:
top2 = 0
val = top1 + top2 + add
add = val // 10
stack_list3.append(val%10)
while stack_list3:
cur.next = ListNode(stack_list3.pop())
cur = cur.next
return h.next
def createList1():
head = ListNode(7)
cur = head
cur.next = ListNode(2)
cur.next.next = ListNode(4)
cur.next.next.next = ListNode(3)
return head
def createList2():
head = ListNode(5)
cur = head
cur.next = ListNode(6)
cur.next.next = ListNode(4)
return head
def printList(head):
cur = head
while cur != None:
print(cur.val, '-->', end='')
cur = cur.next
print('NULL')
if __name__ == "__main__":
l1 = createList1()
printList(l1)
l2 = createList2()
printList(l2)
res = Solution().addTwoNumbers(l1, l2)
printList(res)