Sunday, January 4, 2015

Merge Two Sorted Lists (LeetCode Linked List)

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.

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