首页 > 编程语言 > 详细

leetcode-python-两数相加

时间:2021-06-15 21:20:11      阅读:18      评论:0      收藏:0      [点我收藏+]

先写两个函数:

1)getListNum:因为链表是逆序数字,所以链表逐个入栈,然后出栈组成顺序数字。

2)  List2Link:将数字转换成列表然后从尾部逐个相连。

# Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next

def getListNum(l):
    stack = list()
    while l:
        stack.append(l.val)
        l = l.next
    num = 0
    for i in range(len(stack)):
        num = num * 10 + stack.pop()
    return num

def list2Link(l):
    head = ListNode(int(l.pop()))
    p = head
    while l:
        p.next = ListNode(int(l.pop()))
        p = p.next
    return head

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        return list2Link(list(str(getListNum(l1)+ getListNum(l2))))
        

 

leetcode-python-两数相加

原文:https://www.cnblogs.com/cbachen/p/14886124.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!