Leetcode刷题记录——21. 合并两个有序链表

在这里插入图片描述

题目比较简单
我的思路是:
设置两个指针
l1和l2
分别指向两个链表的下一个待比较节点
先搞一个虚拟头结点faker
将上述faker头结点设为lastnode
此后,比较l1和l2,
把小的一个作为头结点
将小的那个对应的指针后移
若相等 将两个相等节点排列在最前面,并将两个指针都后移

最后 当一个指针指到None时,将lastnode的next指向另一个指针
返回头结点

# 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:

        faker = ListNode(0)
        lastnode = faker
        while l1 is not None and l2 is not None:#l1和l2都不是各自链表的末尾
            if l1.val == l2.val:
                lastnode.next = ListNode(l1.val)
                lastnode.next.next = ListNode(l2.val)
                lastnode = lastnode.next.next
                l1 = l1.next
                l2 = l2.next
            elif l1.val < l2.val:#l1小,先录入l1
                lastnode.next = ListNode(l1.val)
                lastnode = lastnode.next
                l1 = l1.next
            elif l2.val < l1.val:
                lastnode.next = ListNode(l2.val)
                lastnode = lastnode.next
                l2 = l2.next
        if l1 is None and l2 is not None:
            lastnode.next = l2
        elif l2 is None and l1 is not None:
            lastnode.next = l1
        return faker.next
发布了43 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/105331301
今日推荐