美文网首页
[LeetCode]21、合并两个有序的链表

[LeetCode]21、合并两个有序的链表

作者: 河海中最菜 | 来源:发表于2019-07-28 08:44 被阅读0次

题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

思路

  • 递归:
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 
        if l1 and l2:
            if l1.val > l2.val: l1, l2 = l2, l1
            l1.next = self.mergeTwoLists(l1.next, l2)
        return l1 or l2
递归
  • 归并合并
# 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 not l1 and not l2:
            return None
        if not l1 or not l2:
            return l1 or l2
        dummy = ListNode(0)
        p1 = l1
        p2 = l2
        cur = dummy
        while p1 and p2:
            if p1.val > p2.val:
                cur.next = ListNode(p2.val)
                p2 = p2.next
                
            else:
                cur.next = ListNode(p1.val)
                p1 = p1.next
            cur = cur.next
        while p1:
            cur.next = ListNode(p1.val)
            p1 = p1.next
            cur = cur.next
        while p2:
            cur.next = ListNode(p2.val)
            p2 = p2.next
            cur = cur.next
        return dummy.next
归并

相关文章

网友评论

      本文标题:[LeetCode]21、合并两个有序的链表

      本文链接:https://www.haomeiwen.com/subject/ndderctx.html