My 259ms java solution


  • 1
    S

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode p,q,head;
    if(l1==null&&l2==null)
    return null;
    if(l1!=null&&l2==null)
    return l1;
    if(l2!=null&&l1==null)
    return l2;
    if(l1.val<=l2.val){
    p=l1;
    q=l2;
    }
    else{
    p=l2;//guarantee p ponits to the littler
    q=l1;
    }
    head=p;
    while(p.next!=null&&q.next!=null){
    if(p.next.val>q.val){
    ListNode temp=q;
    q=p.next;
    p.next=temp;

            }
            p=p.next;
        }//
        if(q.next!=null)//
            p.next=q;
        else{//
        	while(p.next!=null&&p.next.val<q.val)
        		p=p.next;
        	ListNode temp=q;
            q=p.next;
            p.next=temp;
            p.next.next=q;
        }
        return head;
    }

  • 0
    O

    Please, do this post more readable.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.