题解 | #合并两个排序的链表# - 链表的排序 - 效率比较低, 没有审清题干认真思考

合并两个排序的链表

http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        # write code here
        # 1.将pHead1所在链表的尾部指向pHead2来合并两个链表形成大链表
        # 2.将合并后链表的所有值放入数组中,排序
        # 3.将排序好的数组依次赋值给大链表
        if pHead1 is None:
            return None
        
        cur = pHead1
        while cur.next:
            cur = cur.next
        cur.next = pHead2
        
        point = pHead1
        node_list = []
        while point:
            node_list.append(point.val)
            point = point.next
        print(node_list)
        
        for j in range(len(node_list)-1,0,-1):
            count = 0
            for i in range(j):
                if node_list[i] > node_list[i+1]:
                    node_list[i], node_list[i+1] = node_list[i+1], node_list[i]
                    count += 1
            if count == 0:
                break
        print(node_list)
        
        point2 = pHead1
        i = 0
        while point2:
            point2.val = node_list[i]
            point2 = point2.next
            i += 1
        return pHead1

        
全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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