简体   繁体   中英

C: Swap two nodes of a linked list

I'm having trouble when there are only two nodes (not more) in a linked list that need to be swapped. When displaying this list, the swapping is done however only the last node is displayed. this is part of the code that does the swapping:

typedef struct record
{   
    char name[20];
    char surname[20];
    char telephone[20];

}Record;

typedef struct node
{
    Record data;
    struct node *next;
}Node;

Node *head = NULL;

int cmpRecord(const Record* x, const Record* y) {   
    int cmp = strcmp(x->name, y->name);
    return (cmp > 0) - (cmp < 0);

}

void addRecord(Record x)
{

    Node *previousNode = NULL;
    Node *newNode;
    Node *n;

    newNode = (Node*)malloc(sizeof(Node));  
    newNode->data = x;  
    newNode->next = NULL;   

    if (head == NULL)  // The list is empty
    {
        head = newNode;
    }

Here is the logic for swapping the nodes

    else if (length == 1)
    {
        n = head;
        if (cmpRecord(&n->data.name, &newNode->data.name) > 0)
        {
            newNode->next = n;
            n = newNode;
            return;
        }       

    }

You don't update head , and the cmpRecord call parameters are off. Try

else if (length == 1)
{
    n = head;
    if (cmpRecord(&(n->data), &(newNode->data)) > 0)  //<-- fix types
    {
        newNode->next = n;
        head = newNode; // <---- update head if the new record should be first
        return;
    }       

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM