vendredi 20 juillet 2018

Swapping two nodes of linked list without swapping data in C++

So I'm trying to swap two nodes of linked list..I'm provided with indexes of linked list(starts from 0)..In my code I'm handling many cases but this approach is valid only when j-i<=2..If there is a difference of 3 or more between i and j..I'm not able to handle it..Please help me to correct my approach.

node* swap_nodes(node *head,int i,int j)
{
if(j<i)
{
    int temp;
    temp=i;
    i=j;
    j=temp;
}
node *prev1,*prev2,*temp1,*temp2;
if(i==j)
{
    return head;
}
if(i==0  && abs(i-j)!=1)
{
   int n=0;
   node *temp=head;
   prev1=head;
   temp1=prev1->next;
   while(n<j-1)
   {
       temp=temp->next;
       n++;
   }
   prev2=temp;
   temp2=prev2->next;
   prev2->next=temp1;
   temp1->next=prev1;
   prev1->next=temp2->next;
   temp2->next=prev2;
   return temp2;
 }
 else if(abs(i-j)==1 && i!=0 )
 {
    int n=0;
    node *temp=head;
    while(n<i-1)
    {
       temp=temp->next;
       n++;
    }
    prev1=temp;
    temp1=prev1->next;
    n=0;
    while(n<j-i+1)
    {
       temp=temp->next;
       n++;
    }
    temp2=temp;
    prev1->next=temp2;
    temp1->next=temp2->next;
    temp2->next=temp1;
    return head;
}
else if(i==0 && j==1)
{
    temp1=head;
    temp2=head->next;
    node *temp3=temp2->next;
    temp2->next=temp1;
    temp1->next=temp3;
    return temp2;
}
else
{
   int n=0;
   node *temp=head;
   while(n<i-1)
   {
       temp=temp->next;
       n++;
   }
   prev1=temp;
   temp1=prev1->next;
   n=0;
   while(n<j-i)
   {
       temp=temp->next;
       n++;
   }
   prev2=temp;
   temp2=prev2->next;
   prev1->next=temp2;
   temp1->next=temp2->next;
   temp2->next=prev2;
   prev2->next=temp1;
   return head;
}
}

Aucun commentaire:

Enregistrer un commentaire