【注释详细,思路清晰】【打卡第10天】leetcode热题HOT100之Java实现:21. 合并两个有序链表

1、题目描述

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

2、算法分析

 ① 先创建一个空的链表存储结果集

 ② 比较l1,l2的值,然后存储到链表中

 ③ 如果其中一个链表为空,结果集指针链接另一个链表

 ④ 返回链表的头结点

关于ListNode node = new ListNode(x);的详解,请访问:

https://blog.csdn.net/Sunshineoe/article/details/110371832

3、代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */    

 
class Solution {
    public 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;
                current = current.next;
                l1 = l1.next;
            }else{
                current.next = l2;
                current = current.next;
                l2 = l2.next;
            }
        }

        if(l1 == null){
            current.next = l2;
        }
        if(l2 == null){
            current.next = l1;
        }

        return dummy.next;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值