python 链表相加
时间: 2023-10-23 15:40:13 浏览: 99
(Python3)数据结构–单链表之计算两数之和
给定两个非空链表,表示两个非负整数。每个节点包含一个数字,数字按位逆序存储,使得第一个节点包含最低有效位。
将这两个数字相加并以相同方式返回新的链表。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
Python代码实现:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
val = val1 + val2 + carry
carry = val // 10
curr.next = ListNode(val % 10)
curr = curr.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next
# 测试代码
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
s = Solution()
res = s.addTwoNumbers(l1, l2)
while res:
print(res.val, end=' ')
res = res.next
# 输出:7 0 8
阅读全文