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

后端 未结 26 2940
有刺的猬
有刺的猬 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:29

    Node MergeLists(Node node1, Node node2)
    {
       if(node1 == null)
          return node2;
       else (node2 == null)
          return node1;
    
       Node head;
       if(node1.data < node2.data)
       {
          head = node1;
          node1 = node1.next;
       else
       {
          head = node2;
          node2 = node2.next;
       }
    
       Node current = head;
       while((node1 != null) ||( node2 != null))
       {
          if (node1 == null) {
             current.next = node2;
             return head;
          }
          else if (node2 == null) {
             current.next = node1;
             return head;
          }
    
          if (node1.data < node2.data)
          {
              current.next = node1;
              current = current.next;
    
              node1 = node1.next;
          }
          else
          {
              current.next = node2;
              current = current.next;
    
              node2 = node2.next;
          }
       }
       current.next = NULL // needed to complete the tail of the merged list
       return head;
    
    }
    

提交回复
热议问题