File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode :
2
+ def __init__ (self , val = 0 , next = None ):
3
+ self .val = val
4
+ self .next = next
5
+ def addTwoNumbers (l1 : ListNode , l2 : ListNode ) -> ListNode :
6
+ stack1 , stack2 = [], []
7
+ while l1 :
8
+ stack1 .append (l1 .val )
9
+ l1 = l1 .next
10
+ while l2 :
11
+ stack2 .append (l2 .val )
12
+ l2 = l2 .next
13
+ carry = 0
14
+ result = None
15
+ while stack1 or stack2 or carry :
16
+ val1 = stack1 .pop () if stack1 else 0
17
+ val2 = stack2 .pop () if stack2 else 0
18
+ total = val1 + val2 + carry
19
+ carry = total // 10
20
+ new_node = ListNode (total % 10 )
21
+ new_node .next = result
22
+ result = new_node
23
+ return result
24
+ def create_linked_list (nums ):
25
+ dummy = ListNode ()
26
+ current = dummy
27
+ for num in nums :
28
+ current .next = ListNode (num )
29
+ current = current .next
30
+ return dummy .next
31
+ def print_linked_list (head ):
32
+ while head :
33
+ print (head .val , end = " -> " if head .next else "" )
34
+ head = head .next
35
+ print ()
36
+ l1 = create_linked_list ([7 , 2 , 4 , 3 ])
37
+ l2 = create_linked_list ([5 , 6 , 4 ])
38
+ print ("l1:" )
39
+ print_linked_list (l1 )
40
+ print ("l2:" )
41
+ print_linked_list (l2 )
42
+ result = addTwoNumbers (l1 , l2 )
43
+ print ("Result:" )
44
+ print_linked_list (result )
You can’t perform that action at this time.
0 commit comments