gpt4 book ai didi

c - 将值插入双链表的中间

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:08 25 4
gpt4 key购买 nike

我正在使用 C 语言工作,我正在尝试编写一个程序,从文件中读取行并将它们排序到双链表中。目前我能够正确读取文件,并且在我添加排序功能之前,双链表正在按预期记录值,但由于某种原因,现在我正在尝试将值添加到列表的中间而不是仅仅最后整个列表被最新的输入覆盖。下面是我对数据结构的初始化和插入函数的实现。我使用 ID 参数对节点进行排序,最后如果我输出 ID,它们的顺序是正确的,那只是保存在 val 变量(文件中的一行)中的数据不正确正确保存。谢谢!

typedef struct ListNode {
struct ListNode *next;
struct ListNode *prev;
char *val;
int id;
} ListNode;

typedef struct List {
int count;
ListNode *first;
ListNode *last;
} List;


void List_push(List *list, char *newval, int id)
{
ListNode *node = malloc(sizeof(ListNode));

if(list->count >0) {
printf("First in list is now %s", list->first->val);
}

node->val = newval;
node->id = id;
printf("This value is: %s The id is: %d\n", node->val, node->id);
if(list->last == NULL) {
printf("List is empty, inserting first element\n");
list->first = node;
list->last = node;
}
else if(node->id < list->first->id) {
printf("Value is smaller than first in list\n");
printf("First in list was %s \n", list->first->val);
node->next = list->first;
printf("%s is now second\n", node->next->val);
list->first->prev = node;
printf("First in list is now %s", list->first->prev->val);
list->first = node;
printf("First in list is now %s\n", list->first->val);
printf("Then %s\n", list->first->next->val);
}
else {
node->next = list->first;
printf("Value bigger than first in list\n");
int found = 0;
while((node->next != NULL) && (found ==0)) {
if(node->id < node->next->id) {
found = 1;
}
else {
printf("Still looking\n");
printf("%d\n", node->next->id);
node->next = node->next->next;
}
}
if(found == 1) {
printf("Found location\n");
node->prev = node->next->prev;
node->next->prev = node;
printf("First in list: %d\n", list->first->id);
}
else {
list->last->next = node;
node->prev = list->last;
list->last = node;
}
}

list->count++;
}

最佳答案

Found location block 中,您忘记设置前一个节点的 next;改变

                node->next->prev = node;

                node->prev->next =
node->next->prev = node;

那里。

关于c - 将值插入双链表的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505152/

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