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.
一道简单的链表题,然而我用了太久list<>已经忘记链表怎么做了= =
总而言之非常感谢http://www.cnblogs.com/etcow/archive/2012/09/29/2707908.html这篇文章……让我捡起来好久不用的东西= =
C# Code
public class Solution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode resultList;
ListNode currentNode;
if (l1.val <= l2.val) { resultList = l1; l1 = l1.next; }
else { resultList = l2; l2 = l2.next; }
currentNode = resultList;
while (l1 != null || l2 != null)
{
if (l1 == null)
{
currentNode.next = l2; l2 = l2.next; currentNode = currentNode.next;
continue;
}
if (l2 == null)
{
currentNode.next = l1; l1 = l1.next; currentNode = currentNode.next;
continue;
}
if (l1.val <= l2.val)
{
currentNode.next = l1; l1 = l1.next; currentNode = currentNode.next;
continue;
}
else
{
currentNode.next = l2; l2 = l2.next; currentNode = currentNode.next;
continue;
}
}
return resultList;
}
}