Leetcode2:Add Two Numbers@Python

时间:2022-08-08 17:37:10

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

 #-*-coding:utf-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
"""
tens = 0 # l1.val+l2.val所得和的十位数,初始化0
units = 0 # l1.val+l2.val所得和的个位数,初始化0
l_origin = ListNode(0) # 表示一个链表的头结点
l = l_origin
while(l1 or l2 or tens!=0):
val = tens
if l1:
val = val + l1.val
l1 = l1.next
if l2:
val = val + l2.val
l2 = l2.next
units = val % 10
tens = val / 10
node = ListNode(units)
l.next = node
l = l.next
return l_origin.next # 返回所求列表

在Leetcode上提交时直接提交Solution类,结点定义不用提交。

在做这题时用到带有头结点的链表,比不带头结点的链表使用时方便的多。