gpt4 book ai didi

c - 如何将新创建的节点添加到链表中?

转载 作者:行者123 更新时间:2023-11-30 16:01:43 25 4
gpt4 key购买 nike

这是我的代码,我只能将节点添加到链表的头部,但是如何将节点追加到链表的尾部?谢谢

struct recordNode {
char name[256];
char event[128]; /
float time;
struct recordNode* next;
};

struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;

struct recordNode* createRecord(char* name, char* event, float time) {

temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;

/* link up */
if (aRecordPointer == NULL) {
aRecordPointer = temp;
temp->next = NULL;
} else {
temp->next = aRecordPointer;
aRecordPointer = temp;
}

return aRecordPointer;

}

int main() {

struct recordNode* record = createRecord("1abc", "abc", 12.25);
record = createRecord("2abc", "abc", 25.98);
record = createRecord("3abc", "abc", 52.60);

}

/* now result:

3abc abc 12.25
2abc abc 25.98
1abc abc 52.60

needed result:

1abc abc 52.6
2abc abc 25.98
3abc abc 12.25

*/

最佳答案

假设 aRecordPointer 是指向列表头(第一个)元素的指针,您需要从头到尾(最后一个)迭代列表。

struct recordNode* createRecord(char* name, char* event, float time){ 
temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;
temp->next = NULL;

if (aRecordPointer == NULL) {
aRecordPointer = temp;
}
else {
struct recordNode* pLast = aRecordPointer;

/* find the last element */
while(pLast->next != NULL) {
pLast = pLast->next;
}

/* get linked */
pLast->next = temp;
}

return aRecordPointer;
}

关于c - 如何将新创建的节点添加到链表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6197408/

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