21. Merge Two Sorted Lists

/**
 * 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 head=null;
        ListNode t1=l1;
        ListNode tail=null;
        ListNode t2=l2;
        while(t1!=null&&t2!=null)
        {
            if(t1.val<=t2.val)
            {
                if(head==null)
                    head=t1;
                else
                    tail.next=t1;
                tail=t1;
                t1=t1.next;
                
            }
            else
            {
                if(head==null)
                    head=t2;
                else
                    tail.next=t2;
                tail=t2;
                t2=t2.next;
            }
        }
        while(t1!=null)
        {
            tail.next=t1;
            tail=t1;
            t1=t1.next;
        }
        while(t2!=null)
        {
            tail.next=t2;
            tail=t2;
            t2=t2.next;
        }
        return head;
        
    }
}

 

posted @ 2016-04-04 13:59  阿怪123  阅读(96)  评论(0)    收藏  举报