题目
原题地址https://leetcode-cn.com/problems/add-two-numbers/
解答
Python实现单向无序链表(Singly linked list)可参考链接
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
将单向无序链表转为字符串形式。利用字符串转换成整数形式相加,再转成字符串,最后输出链表形式。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def lNstr(lN):#把链表lN变成字符串
if lN.next==None:
return str(lN.val)
else:
return str(lN.val)+str(lNstr(lN.next))
def strlN(str0):#把字符串str0变成链表
if len(str0)==1:
return ListNode(int(str0))
else:
lN = ListNode(int(str0[0]))
lN.next = strlN(str0[1:])
return lN
str1 = lNstr(l1)[::-1]
str2 = lNstr(l2)[::-1]
strSUM = str(int(str1)+int(str2))[::-1]
return strlN(strSUM)
实际效果