swap in doppelt verknüpfter Liste
Ich versuche, zwei Knoten in einer doppelt verknüpften Liste auszutauschen. Unten ist der Teil des Programms mit Swap-Funktion.
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;
}
Wenn ich dieses Programm ausführe, stürzt es im Falle des 1. und 2. Knotens ab. Im Falle eines anderen Knotens wird eine Endlosschleifenausgabe ausgegeben. (zB: - 2-> 4 2-> 4 2-> 4 .... usw.) `.
Ich weiß, dass es weitere Fragen zu Knotentausch gibt, aber ich habe keine gefunden, die meinem Problem ähnelt. Bitte hilf mir..!
Danke im Voraus