合并两个有序链表

1、

public class MergeTwoSortedLists {

    // 方法:合并两个有序链表
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 创建一个虚拟节点作为合并后链表的头节点
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        // 遍历两个链表,依次取出较小的节点加入合并后的链表
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }

        // 如果有一个链表还剩下节点,直接连接到合并后的链表尾部
        if (l1 != null) {
            current.next = l1;
        } else {
            current.next = l2;
        }

        // 返回合并后的链表的头节点
        return dummy.next;
    }

 

 

 

2、递归

public class MergeTwoSortedLists {

    // 方法:递归合并两个有序链表
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 如果其中一个链表为空,则返回另一个链表
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

 

 
posted @ 2024-08-14 09:35  抽象Java  阅读(3)  评论(0编辑  收藏  举报