我在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++;
}
答案 0 :(得分:0)
在Found location
区块中,您忘记设置上一个节点的next
;变化
node->next->prev = node;
到
node->prev->next =
node->next->prev = node;
那里。
答案 1 :(得分:0)
将一个节点插入链表中间的长短是这样的:
node_new
)node_new->next = node->next
node_new->prev = node
node->next = node_new
node_new->next
不为空,那么你说node_new->next->prev = node_new
;这是因为如果node_new->next == NULL
那么它没有prev
字段。这是一项非常重要的检查;如果你不这样做,你可能会遇到非常严重的问题!