Leetcode 21. Merge Two Sorted Lists

本文介绍了一种使用Java实现的合并两个有序链表的方法。通过将一个链表作为主链表,将另一个链表的元素依次插入,最终形成一个新的有序链表。文章详细解释了处理过程及代码实现。

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

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

题意:这是一道比简单的题,就是合并两个有序列表

但是由于我对java不熟,同时java没有指针这种东西,所以处理起来稍微费一点劲。

这里,我主要是通过将一条列表作为主列表,将另一个列表的元素依次插入。

代码:

/**
 * 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) {
         if(l1==null) return l2;
             int flag=0;
         ListNode header=l1;

         ListNode pre=l1;
         while(l1!=null&&l2!=null){
             if(l1.val>=l2.val){
                 ListNode temp=new ListNode(0);
                 temp.val=l2.val;
                 if(flag==0){
                     temp.next=l1;
                     header=temp;
                     flag=1;
                     pre=header;
                 }
                 else{
                     
                     pre.next=temp;
                     temp.next=l1;
                     pre=temp;
                 }
                 l2=l2.next;
             }
             else{
                 flag=1;
                 pre=l1;
                 l1=l1.next;
             }
         }
         if(l2!=null){
             pre.next=l2;
         }
         return header;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值