Idea: The idea is quite intuitive. First initial a dummy head. Then compare the heads of l1 and l2 and drag the smaller of the two from the list, push the head pointing to the "victim" forward.
Time: O(n) Space: O(1)
Code:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy=new ListNode(0);
ListNode cur=dummy;
while(l1!=null&&l2!=null)
{
int v1=l1.val;
int v2=l2.val;
if(v1<=v2)
{
cur.next=l1;
l1=l1.next;
}
else
{
cur.next=l2;
l2=l2.next;
}
cur=cur.next;
}
if(l1!=null)
cur.next=l1;
if(l2!=null)
cur.next=l2;
return dummy.next;
}
}
No comments:
Post a Comment