题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 :
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
算法实现
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
var listHead = new ListNode(0);
ListNode curr = listHead;
int x, y;
while (l1 != null || l2 != null)
{
x = (l1 != null) ? l1.val : int.MaxValue;
y = (l2 != null) ? l2.val : int.MaxValue;
if (x < y)
{
curr.next = new ListNode(x);
if (l1 != null) l1 = l1.next;
}
else
{
curr.next = new ListNode(y);
if (l2 != null) l2 = l2.next;
}
curr = curr.next;
}
return listHead.next;
}
执行结果
执行结果:通过
执行用时 : 128 ms, 在所有 C# 提交中击败了96.12%的用户
内存消耗 : 24.7 MB, 在所有 C# 提交中击败了5.36%的用户