先写两个函数:
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))))
原文:https://www.cnblogs.com/cbachen/p/14886124.html