题目:2. Add Two Numbers
链接:https://leetcode.com/problems/add-two-numbers/description/
大致意思是说,有两个链表保存了两个十进制非负整数,每个链表从头到尾的每个结点保存了这个整数的每一位(从低位到高位),计算两个整数的和并返回表示这个整数的链表。
哈哈还是第一次见python的链表。题目简单主要是记下这个链表的表示方法,想起一句话:python传参都是传对象的引用。
python:
# 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
"""
res = ListNode(-1)
index = res
isGreater = temp = 0
while l1 != None and l2 != None:
temp = (isGreater + l1.val + l2.val)
index.next = ListNode(temp % 10)
isGreater = (temp) // 10
l1, l2, index = l1.next, l2.next, index.next
while l1 != None:
temp = (isGreater + l1.val)
index.next = ListNode(temp % 10)
isGreater = (temp) // 10
l1, index = l1.next, index.next
while l2 != None:
temp = (isGreater + l2.val)
index.next = ListNode(temp % 10)
isGreater = (temp) // 10
l2, index = l2.next, index.next
if l1 == None and l2 == None and isGreater == 1:
index.next = ListNode(1)
return res.next