21. 合并两个有序链表

文章介绍了两种方法合并两个链表,法1通过使用虚拟头节点简化代码结构,法2虽然代码更简洁但逻辑清晰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        tail = ListNode(-1)
        cur = tail
        cur1 = list1
        cur2 = list2
        while cur1 != None and cur2 != None:
            if cur1.val <= cur2.val:
                cur.next, cur1 = cur1, cur1.next
            else:
                cur.next, cur2 = cur2, cur2.next
            cur = cur.next
        cur.next = cur1 if cur1 else cur2
        
        return tail.next

Java

法1:最佳解法,使用虚拟头结点

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(-1); // 虚拟头结点
        ListNode tmp = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                tmp.next = list1;
                list1 = list1.next;
            } else {
                tmp.next = list2;
                list2 = list2.next;
            }
            tmp = tmp.next;
        }
        if (list1 == null) {
            tmp.next = list2;
        }
        if (list2 == null) {
            tmp.next = list1;
        }

        return dummy.next;
    }
}

法2:代码不够简洁

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode cur = null, head = null;
        while (list1 != null || list2 != null) {
            if (head == null) {
                if (list1.val <= list2.val) {
                    head = list1;
                    list1 = list1.next;
                } else {
                    head = list2;
                    list2 = list2.next;
                }
                cur = head;
            }
            if (list1 == null) {
                cur.next = list2;
                break;
            }
            if (list2 == null) {
                cur.next = list1;
                break;
            }
            if (list1.val <= list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }

        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值