题目
给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
题解
通过python类来实现链表的数据存储和关联,遍历两个存储数据的链表获取每个结点的数据并相加,如果有一个链表数据读取相较于另一个链表读完数据,则将以读完的链表节点以0代替
提交代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
head = tail =None
while (l1 != None) | (l2 != None):
n1 = l1.val if l1 else 0
n2 = l2.val if l2 else 0
sum = n1 + n2 + carry
if head == None:
head = ListNode(sum % 10)
tail = head
else:
tail.next = ListNode(sum % 10)
tail = tail.next
carry = sum // 10
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if carry > 0:
tail.next = ListNode(carry)
return head
扩展代码
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class SLinkedList:
def __init__(self):
self.head = None
def addNode_begin(self,val):
newNode = ListNode(val)
newNode.next = self.head
self.head = newNode
def printList(self):
printNode = self.head
while printNode is not None:
print(printNode.val)
printNode = printNode.next
class Solution:
# def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(self, l1: SLinkedList, l2: SLinkedList) -> ListNode:
carry = 0
head = None
tail = None
while (l1.head != None) | (l2.head != None):
n1 = l1.head.val if l1.head else 0
n2 = l2.head.val if l2.head else 0
sum = n1 + n2 + carry
if head == None:
head = ListNode(sum % 10)
tail = head
else:
tail.next = ListNode(sum % 10)
tail = tail.next
carry = sum // 10
if l1.head:
l1.head = l1.head.next
if l2.head:
l2.head = l2.head.next
if carry > 0:
tail.next = ListNode(carry)
return head
if __name__ == "__main__":
sol = Solution()
list = SLinkedList()
l2 = SLinkedList()
# 示例1
# list.head = ListNode(3)
# list.addNode_begin(4)
# list.addNode_begin(2)
# l2.head = ListNode(4)
# l2.addNode_begin(6)
# l2.addNode_begin(5)
# list.printList()
# print("分割线-----------------------")
# l2.printList()
# 示例2
# list.head = ListNode(9)
# list.addNode_begin(9)
# list.addNode_begin(9)
# list.addNode_begin(9)
# list.addNode_begin(9)
# list.addNode_begin(9)
# list.addNode_begin(9)
# l2.head = ListNode(9)
# l2.addNode_begin(9)
# l2.addNode_begin(9)
# l2.addNode_begin(9)
# 示例3
# list.head = ListNode(0)
# l2.head = ListNode(0)
print("l1 + l2 result:")
l3 = sol.addTwoNumbers(list,l2)
while l3 is not None:
print(l3.val)
l3 = l3.next