LeetCode-Easy-021-Merge Two Sorted Lists

这篇博客讨论了如何解决LeetCode上的一个简单问题——合并两个已排序的链表。博主给出了一个使用while循环的解决方案,通过比较两个链表的节点值,将较小的节点添加到结果链表中,直到其中一个链表遍历完,然后将剩余的链表直接追加到结果链表。尽管这种方法可行,但博主认为还有更优雅简洁的实现方式。

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

描述

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

难度

Easy

题目链接:

https://leetcode.com/problems/merge-two-sorted-lists/

思路

合并两个有序链表,重点在 while 循环中,前面增加了两个判断,主要是因为两个链表一起遍历,可能其中一个已经遍历完毕了,此时将另一个链表拼到结果链表后面即可。
正常的逻辑是 if 语句,主要是判断当前两个结点的大小,然后决定哪个链表向后移动一位。

    public static void main(String...args) {
        ListNode l1 = new ListNode(1);
        ListNode l12 = new ListNode(2);
        ListNode l13 = new ListNode(4);
        ListNode l14 = new ListNode(5);
        l1.next = l12;
        l12.next = l13;
        l13.next = l14;
        ListNode l2 = new ListNode(1);
        ListNode l22 = new ListNode(3);
        ListNode l23 = new ListNode(4);
        ListNode l24 = new ListNode(6);
        l2.next = l22;
        l22.next = l23;
        l23.next = l24;
        ListNode ret = mergeTwoLists(l1, l2);
        System.out.println(ret);
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(0), head = node;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                node.next = l2;
                break;
            }
            if (l2 == null) {
                node.next = l1;
                break;
            }
            if (l1.val > l2.val) {
                node.next = l2;
                l2 = l2.next;
            } else {
                node.next = l1;
                l1 = l1.next;
            }
            node = node.next;
        }
        return head.next;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

虽然上面的程序可以解决问题,但是,显然,不够优雅和简练!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值