zoukankan      html  css  js  c++  java
  • 31.leetcode2_add_two_numbers

    1.题目描述


    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.

    将两个链表的各节点的数值依次相加,返回一个新的链表

    Example

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

    2.题目分析

    如果是列表的话,直接转为数字相加再返回列表就可以了。如果是链表的话,这样做就会麻烦很多了。所以还是依次遍历节点求和比较方便

    3.解题思路

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def addTwoNumbers(self, l1, l2):
     9         """
    10         :type l1: ListNode
    11         :type l2: ListNode
    12         :rtype: ListNode
    13         """
    14         head,p1,p2=ListNode(0),l1,l2 #构建一个新链表
    15         tail=head #tail指向新链表尾部
    16         carry=0    #代表进位
    17         while p1!=None and p2!=None: #遍历两个链表公共部分
    18             num=p1.val+p2.val+carry     #求和
    19             if num>9:                            #判断是否需要进位
    20                 num-=10
    21                 carry=1
    22             else:
    23                 carry=0
    24             tail.next=ListNode(num)        #向新链表中添加元素
    25             tail=tail.next                         #尾指针移动
    26             p1=p1.next                           #双指针同时移动
    27             p2=p2.next
    28         while p1!=None:  #判断哪一个链表还没有遍历结束
    29             num=carry+p1.val 
    30             if num>9:
    31                 num-=10
    32                 carry=1
    33             else:
    34                 carry=0
    35             tail.next=ListNode(num) #新链表中添加新元素
    36             tail=tail.next
    37             p1=p1.next
    38         while p2!=None:
    39             num=carry+p2.val
    40             if num>9:
    41                 num-=10
    42                 carry=1
    43             else:
    44                 carry=0
    45             tail.next=ListNode(num)
    46             tail=tail.next
    47             p2=p2.next
    48         if carry==1: #如果最后还有进位1的话,添加在链表尾部
    49             tail.next=ListNode(carry)
    50         head=head.next #删除链表的首节点
    51         return head        #返回链表
  • 相关阅读:
    数据库管理 trove openstack
    Vmware 给虚拟机传脚本并执行
    Vmware 控制脚本
    python 脚本之 IP地址探测
    python 模块之-ffmpeg 中文参数对照表
    VMware ezmomi工具使用
    VS编译器从DLL导出模板类
    Qt5+VS2012编程
    Visual Studio 2012优化
    计算几何
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8460040.html
Copyright © 2011-2022 走看看