I am trying to swap two nodes in a doubly linked list. Below is the part of program having swap function.
int swap (int x, int y)
{
struct node *temp = NULL ;
struct node *ptr1, *ptr2;
temp = (struct node *)malloc(sizeof(struct node));
if (head == NULL )
{
printf("Null Nodes");
}
else
{
ptr1 = ptr2 = head;
int count = 1;
while (count != x)
{
ptr1 = ptr1->next;
count++;
}
int count2 = 1;
while (count2 != y)
{
ptr2 = ptr2->next;
count2++;
}
ptr1->next->prev = ptr2;
ptr1->prev->next = ptr2;
ptr2->next->prev = ptr1;
ptr2->prev->next = ptr1;
temp->prev = ptr1->prev;
ptr1->prev = ptr2->prev;
ptr2->prev = temp->prev;
temp->next = ptr1->next;
ptr1->next = ptr2->next;
ptr2->next = temp->next;
}
return 0;
}
When I run this program, in case of 1st and 2nd node, it crashes. while in case of any other nodes, it gives infinite loop output. (eg:- 2->4 2->4 2->4....so on)`.
I know there are some more questions about node swappings, but I didn't find any one similar to my problem. Please help me out..!!
Thanks in Advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…