链表相加(二)
拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addInList(self, head1: ListNode, head2: ListNode) -> ListNode:
if head1 is None:
return head2
if head2 is None:
return head1
head1 = self.reverse(head1)
head2 = self.reverse(head2)
dummy = ListNode(-1)
cur = dummy
carry = 0
while head1 or head2:
num1 = 0
num2 = 0
if head1:
num1 = head1.val
head1 = head1.next
if head2:
num2 = head2.val
head2 = head2.next
total = num1 + num2 + carry
carry = total // 10
cur.next = ListNode(total % 10)
cur = cur.next
if carry > 0:
cur.next = ListNode(carry)
return self.reverse(dummy.next)
def reverse(self, head):
if head is None:
return head
cur = head
pre = None
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
if __name__ == '__main__':
l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6, ListNode(4)))
s = Solution()
res = s.addInList(l1, l2)
while res is not None:
print(res.val, end=' ')
res = res.next
这个和字符串大数相加挺像,由于链表只能从前往后,于是首先需要反转链表