Leetcode【121】 Merge Two Sorted Lists(Java版)-附测试代码

本文详细解析了如何合并两个有序链表的算法实现,通过一个示例代码展示了具体的步骤和逻辑,包括处理链表长度不一的情况,为读者提供了一个清晰的链表操作指导。

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

/**
 * 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 p = new ListNode(-1);
        ListNode head = p;
        while(l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next; 
            }
            p=p.next;
        }
		//如果l1和l2不一样长,等遍历完后,将p的next指向没遍历完的链表即可
		//比如l1长度是3,1->2->3,l2长度是5 1->2->3->8->9
		//等循环结束时,l1就指向8->9,只要将p.next指向8->9即可
        p.next = (l1 == null ? l2:l1);
        return head.next;
    }
}
package com.company;

public class mergeTwoLists {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(1);
        mergeTwoLists test = new mergeTwoLists();
        ListNode r = test.mergeTwoLists(l1,l2);
        test.print_result(r);
    }

    public void print_result(ListNode l){
        while (l != null){
            System.out.print(l.val);
            l = l.next;
            if (l != null)
                System.out.print("->");
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2){
        ListNode p = new ListNode(-1);
        ListNode head = p;
        while(l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p=p.next;
        }
        //如果l1和l2不一样长,等遍历完后,将p的next指向没遍历完的链表即可
        //比如l1长度是3,1->2->3,l2长度是5 1->2->3->8->9
        //等循环结束时,l1就指向8->9,只要将p.next指向8->9即可
        p.next = (l1 == null ? l2:l1);
        return head.next;
    }
}

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、付费专栏及课程。

余额充值