我是编程新手(第一学期),在这里找到的例子在做作业时总是给我很大帮助!现在,我必须做一个更大的项目,并且我已经读了很多东西,但是我只是无法解决问题。
strtok()
将其排序为结构(通过将从文件读取的数据分配给结构字段,将其放入结构中)pNode=head;
一起定义在主体中]我已尝试仅复制我认为对该问题重要的部分。由于我已经做了很多尝试,甚至不知道在哪里查找错误,因此不胜感激。提前非常感谢!
void read_file(struct node *pNode, FILE *fp) {
struct node *head = pNode;
head->next=NULL;
head->prev=NULL;
/*(fread, strtok_r, strtok,...)*/
while (token1 != NULL) {
//allocating memory for the structs
struct node*new = calloc(1, sizeof(struct node));
*new =*pNode;
while (token2 != NULL) {
new->index = (*token2 - 48);
token2 = strtok(NULL, "\n"); //jump to next token (=next line)
new->name = malloc(sizeof(char)*strlen(new->name)+1);
strcpy(new->name, token2);
token2 = strtok(NULL, "\n");
/*(some more sorting into struct)*/
/*ADD STRUCT TO LIST*/
if (head->next==NULL){
head->next=new;
head->prev=NULL;
new->prev=head;
new->next=NULL;
}
new->next = head->next;
head->next = new;
new->next->prev = new;
new->prev = head;
head->prev = NULL;
pNode=new;
}
token_recipe = strtok_r(NULL, "#", &temp); //jump to next token (=next recipe)
}
printf("\nLinked list in backwards order:\n");
while (pNode != NULL) {
printf("%s ", pNode->name);
pNode= pNode->prev;
}
puts("\n");
}
您在这里遇到了混乱的纠结,我将尽力帮助解决。
if (head->next==NULL){
head->next=new;
head->prev=NULL;
new->prev=head;
new->next=NULL;
}
new->next = head->next;
head->next = new;
new->next->prev = new;
new->prev = head;
head->prev = NULL;
您第一次有head
和new
。 head->next
是NULL
,因此您需要执行if
块中的位并最终显示如下列表:
head new
然后将new->next
指向head->next
...这意味着您将new->next
指向new
。
head new-> new
[new->next->prev = new
因此new->prev
现在也等于new
head-> new new
但是您将其修复后将其指向head
,并将head->prev
设置为NULL
,因为您从未更改过它,所以它可能已经存在。
head new-> new
而且您仍然得到new
的循环循环,将其指向下一个节点。
完全废弃该代码。 pNode
是列表中的上一个节点,最初与head
相同-这是您应该链接到的变量。]>
new->prev = pNode; pNode->next = new;
未指定的上一个和下一个值应该已经设置为
NULL
(因为您正在使用calloc
)或指向内存中的有效位置,因此您无需弄乱它们。] >然后在循环末尾正确执行以下操作
pNode = new;
将列表的末尾指向创建的最新节点。
您还应该摆脱下一行,因为
new
是一个新的新节点-在pNode
中不应复制任何内容,因此,您需要设置下一个和上一个值不需要,因为它们已经正确设置为NULL
。
*new =*pNode;