2015年9月18日星期五

Leetcode 21 Merge Two Sorted Lists

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 1: simple, no explanation
 public class Solution {  
   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {  
     ListNode dummy=new ListNode(0);  
     ListNode i=l1, j=l2, k=dummy;  
     while (i!=null || j!=null) {  
       if (i==null) {  
         k.next=j;  
         j=j.next;  
         k=k.next;  
       }  
       else if (j==null) {  
         k.next=i;  
         i=i.next;  
         k=k.next;  
       }  
       else if (i.val<j.val) {  
         k.next=i;  
         i=i.next;  
         k=k.next;  
       }  
       else {  
         k.next=j;  
         j=j.next;  
         k=k.next;  
       }  
     }  
     return dummy.next;  
   }  
 }  

没有评论:

发表评论