您的位置:首页 > 其它

Easy 21题 Merge Two Sorted Lists(必须重刷!!!)

2016-10-07 07:44 239 查看
QUESTION:

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.

SOLUTION

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
/* if (l1 == null) return l2;
if (l2 == null) return l1;
//we always get the small one
if (l1.val > l2.val)
{
ListNode tmp = l2;
tmp.next = mergeTwoLists(l1, l2.next);
return tmp;
}
else
{
ListNode tmp = l1;
tmp.next = mergeTwoLists(l1.next, l2);
return tmp;
}
*/
if (l1 == null || l2 == null) {
return l1 == null ? l2 : l1;
}
ListNode tmp=null;
ListNode head=null;
if(l1.val>l2.val)
{
head=l2;
l2=l2.next;

}
else
{
head=l1;
l1=l1.next;
}
tmp=head;
while(l1!=null&&l2!=null)
{
if(l1.val>l2.val)
{
tmp.next=l2;
l2=l2.next;
}
else
{
tmp.next=l1;
l1=l1.next;
}
tmp=tmp.next;
System.out.print("123");
}
if(l1==null)
{
tmp.next=l2;
}
else if(l2==null)
{
tmp.next=l1;
}
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: