LeetCode Problem #2

2018年9月9日

#2. Add Two Numbers

问题描述:

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

样例:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

问题分析:

本题难度为Medium!已给出的函数定义为:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

其中l1和l2分别是类ListNode的实例,返回值也是类ListNode的实例;

本题的目标是很简单的两数相加的链表实现,算法(伪代码)如下:

将当前节点初始化为返回列表哑结点(值val任意)
将进位carry初始化为0
声明p和q分别为l1和l2
遍历p和q直到到达p和q的尾部:
    设x为结点p的值,若p为空,则x值为0
    设y为结点q的值,若q为空,则y值为0
    设sum=carry+x+y
    更新carry的值为sum的10位上的数值
    创建一个数值为sum mod 10的新结点,并将其设置为当前结点的下一个结点
    更新当前结点为下一个结点
    更新p和q为下一个结点,若为空,则不变
最后检查carry是否为1,如是,则需要在当前结点后增添一个值为1的结点
返回哑结点的下一个结点

具体的python代码实现如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        res = ListNode(0)
        curr = res
        p = l1
        q = l2
        carry = 0           #初始进位1或0
        
        while p!=None or q!=None:
            x = p.val if p!=None else 0
            y = q.val if q!=None else 0
            sum = carry + x + y
            carry = sum//10              #取整
            curr.next = ListNode(sum%10)
            curr = curr.next

            if p!=None:
                p = p.next
            if q!=None:
                q=q.next
        
        if carry>0:
            curr.next = ListNode(1)

        return res.next

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值