题解 | #链表相加(二)# - Python(最朴素的做法)

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

思路:
1、遍历2个链表取值、相加得到两个之和sum
2、将sum转换为字符串,从左到右取值新建listnode对象的数组
3、遍历listnode数组,组成链表,并返回链表头
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        s1 = ""
        s2 = ""
        
        while head1:
            s1 +=str(head1.val)
            head1 = head1.next
        while head2:
            s2 +=str(head2.val)
            head2 = head2.next
        s = str(int(s1)+int(s2))
        
        l = []
        for i in s:
            l.append(ListNode(int(i)))
        for i in range(len(l)-1):
            l[i].next = l[i+1]

        return l[0]

全部评论

相关推荐

karis_aqa:和hr没关系,都是打工的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务