您的位置:首页 > 其它

Merge Two Linked List

2016-02-03 23:36 295 查看
Given 1-3-5-6-8, 2-4-9, you want to merge to 1-2-3-4-5-6-8-9.

My solution is very naive solution that actually build a new linkedlist, require space O(n).

public ListNode mergeTwoLists(ListNode l1, ListNode l2){
ListNode fakeHead = new ListNode(0);
ListNode cur = fakeHead;
while(l1!=null && l2!=null){
if(l1.val > l2.val){
cur.next = l2;
l2 = l2.next;
}
else{
cur.next = l1;
l1 = l1.next;
}
cur = cur.next;
}
//还要考虑剩下没完的list,比如1-2-3和9-10,cur=1-2-3,但是9-10还没动呢,要再来个cur.next = l1/2。
if(l1!=null){
cur.next = l1;
}
else{
cur.next = l2;
}
return fakeHead.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: