Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion on pointers C (Linked list)

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!

like image 938
ramennoodles Avatar asked Nov 12 '22 02:11

ramennoodles


1 Answers

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.

like image 139
beyrem Avatar answered Nov 14 '22 22:11

beyrem