Write a function that combines two lists by zipping two list

Write a function that combines two lists by zipping two lists together. Zipping is defined as taking one node from one list and then one from the other list and so on in order to form a single list. After execution, the first list in the original call should point to the combined list (function name: Zip)

Solution

Hi, Please find my implementation.

Please let me know in case of any issue:


Node* Zip(Node *head1, Node *head2){

   // base case, if head1 is NULL
   if(head1 == NULL)
       return head2;

   // if head2 is NULL
   if(head2 == NULL)
       return head1;

   Node *newHead = NULL;
   Node current = NULL;

   // initializing newHead with head1
   newHead = head1; // poiniting to head1
   newHead->next = head2;
   current = head2;

   // forwarding one step
   head1 = head1->next;
   head2 = head2->next;

   while(head1 != NULL && head2 != NULL){
       current->next = head1;
       current->next->next = head2;

       current = head2;

       head1 = head1->next;
       head2 = head2->next;
   }

   // copying remaining nodes from head1, if any
   while(head1 != NULL){
       current->next = head1;
       current = head1;
       head1 = head1->next;
   }


   // copying remaining nodes from head2, if any
   while(head2 != NULL){
       current->next = head2;
       current = head2;
       head2 = head2->next;
   }

   return newHead;
  
}

Write a function that combines two lists by zipping two lists together. Zipping is defined as taking one node from one list and then one from the other list and

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site