合并2个有序链表

合并2个有序链表,第1张

合并2个有序链表

合并2个有序链表(附带leetcode测试地址)

源码

package suanfa.lianbiao;

// 测试链接:https://leetcode.com/problems/merge-two-sorted-lists
public class MergeTwoSortedListsTest {

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        ListNode head = l1.val < l2.val ? l1 : l2;
        if (head == l1) {
            l1 = l1.next;
        } else {
            l2 = l2.next;
        }
        ListNode next = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                next.next = l1;
                l1 = l1.next;
            } else {
                next.next = l2;
                l2 = l2.next;
            }
            next = next.next;
        }
        if (l1 != null) {
            next.next = l1;
        }
        if (l2 != null) {
            next.next = l2;
        }
        return head;
    }

    public static class ListNode {
        public int val;
        public ListNode next;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5684753.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存