LeetCode 精选 TOP 面试题(Java 实现)—— 合并两个有序链表

一、题目描述

1.1 题目
  • 合并两个有序链表

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

  • 示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
1.2 知识点
  • 链表
1.3 题目链接

二、解题思路

2.1 自研思路

  比较基础的链表合并题,不赘述。

三、实现代码

3.1 自研实现
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        cur.next = l1 == null ? l2 : l1;
        return head.next;
    }
}
发布了277 篇原创文章 · 获赞 33 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_40697071/article/details/104046290