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大热门项目」
周日「股市币市:本周交易数据分析与最新公告」
联系客服