File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Time: O(m + n)
2+ # Space: O(m + n)
3+
4+ # You are given two linked lists representing two non-negative numbers.
5+ # The most significant digit comes first and each of their nodes contain a single digit.
6+ # Add the two numbers and return it as a linked list.
7+ #
8+ # You may assume the two numbers do not contain any leading zero, except the number 0 itself.
9+ #
10+ # Follow up:
11+ # What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
12+ #
13+ # Example:
14+ #
15+ # Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
16+ # Output: 7 -> 8 -> 0 -> 7
17+
18+ # Definition for singly-linked list.
19+ # class ListNode(object):
20+ # def __init__(self, x):
21+ # self.val = x
22+ # self.next = None
23+
24+ class Solution (object ):
25+ def addTwoNumbers (self , l1 , l2 ):
26+ """
27+ :type l1: ListNode
28+ :type l2: ListNode
29+ :rtype: ListNode
30+ """
31+ stk1 , stk2 = [], []
32+ while l1 :
33+ stk1 .append (l1 .val )
34+ l1 = l1 .next
35+ while l2 :
36+ stk2 .append (l2 .val )
37+ l2 = l2 .next
38+
39+ prev , head = None , None
40+ sum = 0
41+ while stk1 or stk2 :
42+ sum /= 10
43+ if stk1 :
44+ sum += stk1 .pop ()
45+ if stk2 :
46+ sum += stk2 .pop ()
47+
48+ head = ListNode (sum % 10 )
49+ head .next = prev
50+ prev = head
51+
52+ if sum >= 10 :
53+ head = ListNode (sum / 10 )
54+ head .next = prev
55+
56+ return head
You can’t perform that action at this time.
0 commit comments