leetcode 2. 两数相加 整数取模与链表的尾插法

两数相加

返回两数相加的结果,注意链表是从数字的低位到高位,那么相加时直接从后向前即可

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # val代表两数之和 idx用于标记当前位数
        val = 0
        idx = 1
        while l1 != None:
            val = val + idx * l1.val
            l1 = l1.next
            idx = idx * 10
        idx = 1
        while l2 != None:
            val = val + idx * l2.val
            l2 = l2.next 
            idx = idx * 10
        
        # 边界判断: 如果是0可直接返回,如果非0用来当初始化头结点
        head = ListNode(0)
        if val == 0:
            return head 
        last = head
        while val != 0:
            now = ListNode(val%10)
            last.next = now 
            last = now
            val = val / 10;

        return head.next 

链表操作

尾插法,和数字从小到大匹配

猜你喜欢

转载自blog.csdn.net/mistakk/article/details/109264360