21Merge Two Sorted Lists

来源:互联网 发布:网络博文怎么写 编辑:程序博客网 时间:2024/05/16 07:33
/**
 * 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;
        ListNode res = new ListNode(0);
        ListNode rList = res;
        while(l1!=null&&l2!=null){
        if(l1.val<=l2.val){
        res.next = new ListNode(l1.val);
        res = res.next;
        l1 = l1.next;
        }else{
        res.next = new ListNode(l2.val);
        res = res.next;
        l2 = l2.next;
        }
        }
        
        while(l1!=null){
        res.next = new ListNode(l1.val);
    res = res.next;
    l1 = l1.next;
        }
        
        while(l2!=null){
        res.next = new ListNode(l2.val);
    res = res.next;
    l2 = l2.next;
        }
        
        rList = rList.next;
        return rList;
    }
}
0 0