牛客网《剑指offer》之Python2.7实现:合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

依次遍历两个链表,比较两个链表的元素,采用尾插法,小的先插入链表,大的后插入链表

代码

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        phNew = ListNode(0);
        tmp = phNew
        while pHead1 != None and pHead2 != None:
            if pHead1.val > pHead2.val:
                tmp.next = pHead2
                pHead2 = pHead2.next
            else:
                tmp.next = pHead1
                pHead1 = pHead1.next
            tmp = tmp.next		#注意将待插入链表头后移
        if (pHead1 != None):
            tmp.next = pHead1
        if (pHead2 != None):
            tmp.next = pHead2
        return phNew.next

注意

错误代码:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if pHead1 == None or pHead2 == None:	#若其中一个为空,另一个不为空,也是可以满足题意的。见代码下方的测试用例
            return
        phNew = ListNode(0);
        tmp = phNew
        while pHead1 != None and pHead2 != None:
            if pHead1.val > pHead2.val:
                tmp.next = pHead2
                pHead2 = pHead2.next
            else:
                tmp.next = pHead1
                pHead1 = pHead1.next
            tmp = tmp.next
        if (pHead1 != None):
            tmp.next = pHead1
        if (pHead2 != None):
            tmp.next = pHead2
        return phNew.next

测试用例:
{1,3,5},{}

对应输出应该为:

{1,3,5}

你的输出为:

{}

猜你喜欢

转载自blog.csdn.net/ck_101/article/details/82949528
今日推荐