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

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

    LLNode *mergeSorted(LLNode *h1, LLNode *h2) 
    { 
      LLNode *h3=NULL;
      LLNode *h3l;
      if(h1==NULL && h2==NULL)
        return NULL; 
      if(h1==NULL) 
        return h2; 
      if(h2==NULL) 
        return h1; 
      if(h1->datadata) 
      {
        h3=h1;
        h1=h1->next; 
      }
      else 
      { 
        h3=h2; 
        h2=h2->next; 
      }
      LLNode *oh=h3;
      while(h1!=NULL && h2!=NULL) 
      {
        if(h1->datadata) 
        {
          h3->next=h1;
          h3=h3->next;
          h1=h1->next; 
        } 
        else 
        {
          h3->next=h2; 
          h3=h3->next; 
          h2=h2->next; 
        } 
      } 
      if(h1==NULL)
        h3->next=h2;
      if(h2==NULL)
        h3->next=h1;
      return oh;
    }
    

提交回复
热议问题