题解 | 链表相加(二)

链表相加(二)

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

# 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 , pHead1: ListNode, pHead2: ListNode) -> ListNode:
            if pHead1 is None:
                return pHead2
            if pHead2 is None:
                return pHead1
            list1 = []
            list2 = []
            while pHead1:
                list1.append(str(pHead1.val))
                pHead1 = pHead1.next
            while pHead2:
                list2.append(str(pHead2.val))
                pHead2 = pHead2.next
            str1 = "".join(list1)
            str2 = "".join(list2)
            num1 = int(str1)
            num2 = int(str2)
            num = num1 + num2
            # num_str = str(num).split()
            num_str = list(str(num))
            head = ListNode(-1)
            cur = head
            for i in range(len(num_str)):
                value = int(num_str[i])
                cur.next = ListNode(value)
                # cur.val = value
                cur = cur.next
            return head.next

邪修方法

将两个链表都遍历一遍,把val转为字符串类型放入list,再join转为int,进行加法,最后新建虚拟头节点,将结果逐个放入新链表中,完成!!

全部评论

相关推荐

故事和酒66:央企,事少钱少稳定福利好,离家近可以考虑
点赞 评论 收藏
分享
Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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