打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
LeetCode实战:合并两个有序链表

题目英文

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


题目中文

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

示例:

输入:1->2->4, 1->3->4

输出:1->1->2->3->4->4


算法实现

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

public class Solution
{

    public ListNode MergeTwoLists(ListNode l1, ListNode l2)
    
{
        ListNode pHead = new ListNode(int.MaxValue);
        ListNode temp = pHead;

        while (l1 != null && l2 != null)
        {
            if (l1.val < l2.val)
            {
                temp.next = l1;
                l1 = l1.next;
            }
            else
            {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }

        if (l1 != null)
            temp.next = l1;

        if (l2 != null)
            temp.next = l2;

        return pHead.next;
    }
}

实验结果

提交记录

相关图文


经过8年多的发展,LSGO软件技术团队在「地理信息系统」、「数据统计分析」、「计算机视觉」等领域积累了丰富的研发经验,也建立了人才培养的完备体系,欢迎对计算机技术感兴趣的同学加入,与我们共同成长进步。

我们图文推送的计划如下,欢迎大家转发!

  • 周一「图书排行:计算机书籍每周销量排行榜」

  • 周二「技术分享:C#语言在工程中的应用」

  • 周三「资料分享:网络上发现的电子资料」

  • 周四「LeetCode实战:算法题目的实现

  • 周五「猫眼电影:即将上映、最受期待榜」

  • 周六「Github精选:本周10大热门项目」

  • 周日「股市币市:本周交易数据分析与最新公告」

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
剑指offer 56删除链表中重复的结点
删除链表中重复的结点
LeetCode-Algorithms #002 Add Two Numbers, Database #176 Second Highest Salary
​LeetCode刷题实战203:移除链表元素
剑指offer(C++)-JZ23:链表中环的入口结点(数据结构-链表)
链表算法面试问题?看我就够了!
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服