Java Solution, Just remember one point, adding smaller node to the next of pcur.


  • 1
    public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode cur1=l1;
        ListNode cur2=l2;
        ListNode head,pcur=null;
        if(cur1.val<cur2.val) head=cur1;
        else head=cur2;
        while(cur1!=null&&cur2!=null){
            if(cur1.val<cur2.val){
                if(pcur==null)
                    pcur=cur1;
                else pcur.next=cur1;
                pcur=cur1;
                cur1=cur1.next;
            }
            else{
                if(pcur==null)
                    pcur=cur2;
                else pcur.next=cur2;
                pcur=cur2;
                cur2=cur2.next;
            }
        
        }
    //And don't forget to handle the remaining nodes.
        if(cur1!=null) pcur.next=cur1;
        if(cur2!=null) pcur.next=cur2;
       return head;
    }
    

    }


Log in to reply
 

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