回顾一下,链表: 445. Add Two Numbers II 这个题目,最开始就考虑反转链表,但是题目不允许,我采取了用 栈 把链表里的数取出来的做法。。 后面的做法和 add two numbers 1 差不多了
class ListNode(object): def __init__(self, x): self.val = x self.next = None#445. Add Two Numbers IIclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ stack1,stack2=[],[] while l1: stack1.append(l1.val) l1=l1.next while l2: stack2.append(l2.val) l2=l2.next start=ListNode(0) carry=0 while stack1 or stack2 or carry: if stack1: carry+=stack1.pop() if stack2: carry+=stack2.pop() carry,val=divmod(carry,10) newnode=ListNode(val) newnode.next=start.next start.next=newnode return start.nextclass Solution(object): def addTwoNumbers(self, l1, l2): carry = 0; res = n = ListNode(0); while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next; if l2: carry += l2.val; l2 = l2.next; carry, val = divmod(carry, 10) n.next = n = ListNode(val); return res.next;新闻热点
疑难解答