Interview Question: Merge two sorted singly linked lists without creating new nodes

后端 未结 26 3028
有刺的猬
有刺的猬 2020-12-02 04:09

This is a programming question asked during a written test for an interview. \"You have two singly linked lists that are already sorted, you have to merge them and return a

26条回答
  •  青春惊慌失措
    2020-12-02 04:28

    Node MergeLists(Node list1, Node list2) {
        //if list is null return other list 
       if(list1 == null)
       {
          return list2;
       }
       else if(list2 == null)
       {
          return list1;
       }
       else
       {
            Node head;
            //Take head pointer to the node which has smaller first data node
            if(list1.data < list2.data)
            {
                head = list1;
                list1 = list1.next;
            }
            else
            {
               head = list2;
               list2 = list2.next;
            }
            Node current = head;
            //loop till both list are not pointing to null
            while(list1 != null || list2 != null)
            {
                //if list1 is null, point rest of list2 by current pointer 
                if(list1 == null){
                   current.next = list2;
                   return head;
                }
                //if list2 is null, point rest of list1 by current pointer 
                else if(list2 == null){
                   current.next = list1;
                   return head;
                }
                //compare if list1 node data is smaller than list2 node data, list1 node will be
                //pointed by current pointer
                else if(list1.data < list2.data)
                {
                    current.next = list1;
                    current = current.next;
                    list1 = list1.next;
                }
                else
                {
                    current.next = list2;
                    current = current.next;
                    list2 = list2.next;
                }
            }      
        return head;
        }      
    }
    

提交回复
热议问题