题目
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.
解
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
def toint(node):
# 递归
return node.val + 10 * toint(node.next) if node else 0
n = toint(l1) + toint(l2)
first = last = ListNode(n % 10)
while n > 9:
n //= 10
last.next = last = ListNode(n % 10)
# =============================================================================
# # 链式赋值,等价于以下三行。目的:令last.next 与 last先后指向同一地址
# tmp=ListNode(i)
# last.next=tmp
# last=tmp
# =============================================================================
return first
# Test
class LinkList:
def __init__(self):
self.head=None
def initList(self, data):
# 创建头结点
self.head = ListNode(data[0])
r = self.head # 头结点
p = self.head # 指针
# p作为指针,逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
# node = ListNode(i)
# p.next = node
# p = p.next
p.next = p = ListNode(i) # 与上面3行等价(tmp=ListNode(i),p.next=tmp,p=tmp)
return r
def printlist(self,head):
if head == None: return
node = head
while node != None:
print(node.val,end='')
node = node.next
data1 = list(range(3,9,3))
data2 = list(range(1,10,3))
LL = LinkList()
l1 = LL.initList(data1)
l2 = LL.initList(data2)
LL.printlist(l1)
LL.printlist(l2)
S = Solution()
l_res = S.addTwoNumbers(l1,l2)
LL.printlist(l_res)
Solution来源于 StefanPochmann的Python for the win
LinkList来源于 Python 单链表的初始化、赋值、输出