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
 
posted @ 2021-01-11 00:39  风不再来  阅读(103)  评论(0编辑  收藏  举报