I was trying to do this [question][1] on geeks for geeks. Can someone please tell me what is wrong with my code:
void pairWiseSwap(struct node *head)
{
if(head==NULL||head->next==NULL)
return;
node *i,*j,*tf,*prev;
i=head;
j=i->next;
head=j;
prev=NULL;
while(j!=NULL)
{
if(prev==NULL)
{
tf=j->next;
j->next=i;
i->next=tf;
}
else
{
tf=j->next;
j->next=i;
i->next=tf;
prev->next=j;
}
prev=i;
i=tf;
if(i==NULL)
break;
j=i->next;
}
}
I am trying to swap nodes instead of their data.
Any suggestion
[1]: https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/
1 Like
Your code is working fine but your head is not update in main function but your head is not update in main so your 2nd element is missing. To check correctness of your code try
printList(head); from pairWiseSwap function and then from main you will get to know the problem.
Add these lines in your code
struct Node *tmp=start->next;
pairWiseSwap(start);
start = tmp;
and then try printing it will work fine.
Also be careful about corner case when no of elements is list is only 1 or 2. Because above (my steps) code assumes more than 2 elements. So, I keep corner case for you.
Edit more easy was No problem of corner case use this template.
struct Node * pairWiseSwap(struct Node *head)
add returh head; //at each return in function
//in main call by
start=pairWiseSwap(start);
1 Like
The problem is I don’t have any information about the main function. This is just a function problem as given in the link above. Also I am handling the corner cases but I can’t find a way to update head.
Thanks for your help:)
Then for first two values you have to go by changing data. And rest can be updated using your code.
OK.THANKS FOR YOUR TIME SIR:)
1 Like
Welcome @pavitra_ag sir. Happy Coding