JAVA----------Easy Version To Understand!!!!!!!!


  • 0
    H
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    	if(l1==null)
    		return l2;
    	if(l2==null)
    		return l1;
    	ListNode headNode=new ListNode(0);
    	ListNode head=headNode;
    	head.next=null;
    	ListNode r=head,p=l1,q=l2;
    	while(p!=null&&q!=null){
    		if(p.val<=q.val){
    			r.next=p;
    		    r=r.next;
    		    p=p.next;
    		}
    		else{
    			r.next=q;
    			r=r.next;
    			q=q.next;
    		}
    	}
    	if(p!=null)
    		r.next=p;
    	else
    		r.next=q;
        return head.next;
    }

  • 0
    J

    I am a little confused. Why does it need 'head' here? Can we return 'headNode.next' ?


Log in to reply
 

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