Cloning a linkedlist

Problem Link

/*  the node structure is as follows
struct Node
{
int data;
Node* next;
Node* arb;
};*/

// Should return the head of the copied linked list the
//output will be 1 if successfully copied
Node * copyList(Node *head)
{
     // Your code here
     Node *chead=new Node;
     Node *tmp,*nNode,*a;
     Node *arr[101];
     int val;
     if(head==NULL)
     return chead=NULL;

     chead->data=head->data;
     nNode=chead;
     tmp=head->next;
     arr[chead->data]=chead;
     while(tmp)
     {
         nNode->next=new Node;
         nNode=nNode->next;
         nNode->data=tmp->data;
         arr[nNode->data]=nNode;
         tmp=tmp->next;
     }
     tmp=head;
     nNode=chead;
     while(tmp)
     {
         if(tmp->arb)
         {
             a=tmp->arb;
             val=a->data;
             nNode->arb=arr[val];
         }
         tmp=tmp->next;
         nNode=nNode->next;
     }
     return chead;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *