I'm trying to swap the addresses of two adjacent nodes in a linked list. I tried swapping their values, using an int temp variable and it works perfectly fine. But now, I want to swap two addresses through pointers. Unfortunately, it created an infinite loop inside my while loop. Here's my code snippet:
Using int: //Worked perfectly fine
node* swapNumbers(node* head, int data){
int temp;
node *cursor = head;
while(cursor!=NULL){
if(cursor->data == data){
temp = cursor->data;
cursor->data = cursor->next->data;
cursor->next->data = temp;
//printf("1: %d\n", cursor->data);
//printf("2: %d\n", cursor->next->data);
return cursor;
}
cursor = cursor->next;
}
return NULL;
}
Using addresses: // This created an infinite loop!
node* swapNumbers(node* head, int data){
node *temp = NULL;
node *cursor = head;
while(cursor!=NULL){
if(cursor->data == data){
temp = cursor;
cursor = cursor->next;
cursor->next = temp;
return cursor;
}
cursor = cursor->next;
}
return NULL;
}
my typedef struct contains the following:
typedef struct node
{
int data;
struct node* next;
} node;
I'm new to C and pointers are still confusing me. Any help will be appreciated!
For it not to go into an infinite loop, you need to save the predecessor value of cursor
in a temporary value pointed by another pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With