标签搜索

目 录CONTENT

文章目录

[leetcode]合并两个有序链表题解

沙漠渔
2022-05-11 08:40:26 / 0 评论 / 1 点赞 / 490 阅读 / 1,954 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-05-11,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

 

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

 

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1 和 l2 均按 非递减顺序 排列
Related Topics
  • 递归
  • 链表
  • 解决方案

    package leetcode.editor.cn;
    
    /**
     * 合并两个有序链表
     *
     * @author 沙漠渔
     * @date 2022-01-25 12:06:35
     */
    public class 合并两个有序链表 {
        static
    //leetcode submit region begin(Prohibit modification and deletion)
        class Solution {
            public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
                if (list1 == null) {
                    return list2;
                }
                if (list2 == null) {
                    return list1;
                }
    
                if (list1.val < list2.val) {
                    list1.next = mergeTwoLists(list1.next, list2);
                    return list1;
                } else {
                    list2.next = mergeTwoLists(list2.next, list1);
                    return list2;
                }
            }
        }
    //leetcode submit region end(Prohibit modification and deletion)
    
        static class ListNode {
            int val;
            ListNode next;
    
            public ListNode(int val) {
                this.val = val;
            }
    
            public ListNode(int val, ListNode next) {
                this.val = val;
                this.next = next;
            }
        }
    
        /**
         * 最终测试主方法
         */
        public static void main(String[] args) {
            Solution solution = new Solution();
            ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
            ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
            ListNode listNode = solution.mergeTwoLists(list1, list2);
            for (ListNode i = listNode; i != null; i = i.next) {
                if (i.next == null) {
                    System.out.println(i.val + " ");
                } else {
                    System.out.print(i.val + " ");
                }
            }
        }
    }
    
    1
    广告 广告

    评论区