Why is always time limit error


  • 0
    Y

    public class Solution {
    ListNode mergeTwoLists(ListNode head1,ListNode head2){
    if(head1==null&&head2!=null){
    return head2;
    }
    if(head2==null&&head1!=null){
    return head1;
    }
    if(head1==null&&head2==null)
    return null;
    ListNode newpointer=new ListNode(0);
    ListNode p=newpointer;
    while(head1!=null&&head2!=null){
    if(head1.val<head2.val){
    p.next=head1;
    p=p.next;
    head1=head1.next;
    }
    else{
    p.next=head2;
    p=p.next;
    head2=head2.next;
    }
    }
    if(head1==null)
    p.next=head2;
    if(head2==null)
    p.next=head1;
    return newpointer.next;
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0)
            return null;
        ListNode head=lists[0];
        for(int i=1;i<lists.length;i++){
            head=mergeTwoLists(head,lists[i]);
        }
        return head;
        
    }
    

    }


Log in to reply
 

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