gpt4 book ai didi

C:交换链表的两个节点

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:18 24 4
gpt4 key购买 nike

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

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

}

最佳答案

您不更新 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;
}

}

关于C:交换链表的两个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com