zoukankan      html  css  js  c++  java
  • 167. 链表求和

    167. 链表求和

    中文English

    你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

    样例

    样例 1:

    输入: 7->1->6->null, 5->9->2->null
    输出: 2->1->9->null	
    样例解释: 617 + 295 = 912, 912 转换成链表:  2->1->9->null
    

    样例 2:

    输入:  3->1->5->null, 5->9->2->null
    输出: 8->0->8->null	
    样例解释: 513 + 295 = 808, 808 转换成链表: 8->0->8->null

    """
    Definition of ListNode
    class ListNode(object):
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    
    class Solution:
        """
        @param l1: the first list
        @param l2: the second list
        @return: the sum list of l1 and l2 
        """
        def addLists(self, l1, l2):
            # write your code here
            #先计算, 在生成链表
            l1_str, l2_str = '', ''
            while l1:
                l1_str += str(l1.val)
                l1 = l1.next
            
            while l2:
                l2_str += str(l2.val)
                l2 = l2.next
            
            new_str = str(int(l1_str[:: -1]) + int(l2_str[:: -1]))[:: -1]
            
            new_head = ListNode(0)
            tail = new_head
            
            for s in new_str:
                node = ListNode(int(s))
                tail.next = node 
                tail = tail.next
            
            return new_head.next
     
  • 相关阅读:
    后向边
    图的割点、桥和双连通分支的基本概念
    Hihocoder 1062 最近公共祖先1
    会场问题 差分解法
    POJ2976 01分数规划 普通题
    Hihocoder 1049
    hihocoder 1050树中最长路
    Hihocoder 1055
    POJ1463
    C语言|博课作业02
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14260321.html
Copyright © 2011-2022 走看看