合并两个有序链表Python3

9次阅读

共计 737 个字符,预计需要花费 2 分钟才能阅读完成。

提出问题:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解决思路:合并链表很简单,设置两个指针遍历两个链表,同时遍历并比较大小,如果 1 链表的当前节点值较小,将该节点添加到新链表中,1 链表遍历指针后移一位,直到两个链表内所有节点都添加到新链表中。注意:题目要求新链表是通过拼接给定的两个链表的所有节点组成的,所以初始新建一个头节点,将头节点下一个节点指针指向两个链表中的最小节点,最后返回头节点的下一个节点。

代码如下 (~▽~):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1==None:
            return l2
        elif l2==None:
            return l1
        else:
            h1 = l1
            h2 = l2
            head = ListNode(0)
            result = head
            while h1!=None and h2!=None:
                if h1.val <= h2.val:
                    head.next = h1
                    h1 = h1.next
                else:
                    head.next = h2
                    h2 = h2.next
                head = head.next
            if h1!=None:
                head.next = h1
            if h2!=None:
                head.next = h2
        return result.next

时间与空间复杂度:

题目来源:https://leetcode-cn.com/probl…

正文完
 0