题目
给你两个非空的链表,表示两个非负的整数。
它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
复习单链表
# 知乎链表https://zhuanlan.zhihu.com/p/60057180
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class SingleLinkNode(object):
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def length(self):
count = 0
cur = self._head
while cur is not None:
count += 1
cur = cur.next
return count
def items(self):
list = []
cur = self._head
while cur is not None:
list.append(cur.val)
cur = cur.next
return list
def add_end(self, val):
node = Node(val)
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next is not None:
cur = cur.next
cur.next = node
def add_head(self, val):
node = Node(val)
node.next = self._head
self._head = node
def insert(self, index, val):
if index <= 0:
self.add_head(val)
elif index > (self.length() - 1):
self.add_end(val)
else:
node = Node(val)
cur = self._head
for _ in range(index - 1):
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, val):
cur = self._head
pre = None
while cur is not None:
if cur.val == val:
if not pre:
self._head = cur.next
else:
pre.next = cur.next
return True
else:
pre = cur
cur = cur.next
def find(self, val):
return val in self.items()
if __name__ == '__main__':
link = SingleLinkNode()
for i in range(5):
link.add_end(i)
link.add_head(6)
print(link.items())
link.insert(4, 9)
print(link.items())
link.remove(0)
print(link.items())
题解
My_CODE:
# 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:
flag = 0
link = ListNode(0)
r = link
while l1 is not None or l2 is not None:
if l1 is None:
sum = l2.val + flag
elif l2 is None:
sum = l1.val + flag
else:
sum = l1.val + l2.val + flag
if sum >= 10:
r.next = ListNode(sum % 10)
r = r.next
flag = 1
else:
r.next = ListNode(sum)
r = r.next
flag = 0
l1 = None if l1 is None else l1.next
l2 = None if l2 is None else l2.next
if flag == 1:
r.next = ListNode(1)
r = r.next
return link.next
Other
其他人的想法是在较短的链表中用0进行补齐再进行对应位相加。