分类:LinkedList
考察知识点:LinkedList
最优解时间复杂度:**O(n) **
2. Add Two Numbers
-
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
代码:
解法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
res=ListNode(0)
resp=res
sum_=0
p1=l1
p2=l2
while(p1!=None or p2!=None):
if(p1!=None):
sum_+=p1.val
p1=p1.next
if(p2!=None):
sum_+=p2.val
p2=p2.next
resp.next=ListNode(sum_%10)
sum_//=10
resp=resp.next
if sum_==1:
resp.next=ListNode(1)
return res.next
讨论:
1.太简单的几乎不用懂脑子
002