C:交换链表的两个节点

时间:2016-04-17 20:59:18

标签: c sorting pointers struct nodes

当链接列表中只有两个节点(不是更多)需要交换时,我遇到了麻烦。显示此列表时,交换完成,但只显示最后一个节点。 这是进行交换的代码的一部分:

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;
    }

这是交换节点的逻辑

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

    }

1 个答案:

答案 0 :(得分:2)

您不会更新head,并且cmpRecord来电参数已关闭。尝试

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;
    }       

}