Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:
给定两个链表,按位相加。
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p1 = l1
p2 = l2
end = None
pn = 0
n = 0
nm = 0
isFirst = True
while p1 or p2:
if p1 and p2:
n = p1.val + p2.val + pn
nm = n % 10
pn = n / 10
p1.val = nm
end = p1
p1 = p1.next
p2 = p2.next
elif p1:
n = p1.val + pn
nm = n % 10
pn = n / 10
p1.val = nm
end = p1
p1 = p1.next
else:
n = p2.val + pn
nm = n % 10
pn = n / 10
p2.val = nm
if isFirst:
end.next = p2
isFirst = False
end = p2
p2 = p2.next
if pn:
end.next = ListNode(pn)
return l1

本文介绍了一个通过Python实现的算法,用于将两个链表表示的非负整数相加,并返回结果作为新的链表。详细解释了算法逻辑,包括链表节点的初始化、遍历、加法运算和进位处理。
5457

被折叠的 条评论
为什么被折叠?



