I want to merge 2 linked list into 1.
Is the code below ok? Can you Check please?

LIST Merge_List(LIST P,LIST Q)
{
     HEADER h = P;
     NODEPTR ptr2 =Q;
     NODEPTR ptr1 = P;
     NODEPTR prev=P;
     NODEPTR temp=NULL;

     /* Second List Pointer */
     while(ptr2 != NULL)
     {
          /* First List Pointer */
          while(ptr1 != NULL)
          {
               while(ptr2->Age>ptr1->Age)
               {
                    prev = ptr1;
                    ptr1 = ptr1->Next;
               }
               if(prev == ptr1)
               {
                    // This means the first node of the header needs to be changed
                    temp = New_Node();
                    temp->Age = ptr2->Age;
                    temp->Next = prev;
                    prev = temp;
                    h = temp;
               }
               else
               {
                    temp = New_Node();
                    temp->Age = ptr2->Age;

                    temp->Next = prev->Next;
                    prev->Next = temp;
               }
               break;
          }
          ptr2 = ptr2->Next;
     }
     return h;
}

>Is the code below ok?
It depends on the definition of your types (which is confusing because they all seem to be the same thing) and what exactly you're trying to do. When you merge, do both lists have to remain unchanged? Generally, this is an acceptable merge:

struct node *merge ( struct node *a, struct node *b )
{
  struct node c;
  struct node *it = &c;

  while ( a != NULL && b != NULL ) {
    if ( a->Age < b->Age ) {
      it->next = a;
      a = a->next;
    }
    else {
      it->next = b;
      b = b->next;
    }

    it = it->next;
  }

  if ( a == NULL )
    it->next = b;
  else
    it->next = a;

  return c.next;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.