我正在尝试写一个程序,从excel文件中导入数据,并将名称存储在链表中。第一列包含命令{ add,remove,flush},如果命令为add,则第二列包含名称。
它将名称添加到列表的末尾,从前面删除名称,并在刷新时从内存中删除整个列表。Add检测名称是否已包含(尚未写入),flush和remove还检测队列是否为空。
示例文件:
add dave
add mike
remove
add paul
flush
add steve输出示例:
add: dave
add: dave, mike
remove: mike
flushing queue
add: steve我的问题是我的flush命令没有正确删除列表。代码必须与c89兼容。感谢您所能提供的任何帮助。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
struct node* next;
char name[50];
};
struct node* addNode(char *word);
void freeNodes(struct node* head);
void removeNode (struct node* head);
int main(void)
{
struct node* head = NULL, *tail, *temp;
char buffer[50];
int i;
char *word = " ";
char *del = " ,\n";
FILE *fp;
fp = fopen("queue-data.csv", "r");
while( fgets(buffer, sizeof(buffer), fp) != NULL )
{
word = strtok(buffer, del);
/******** ADD *********/
if( strcmp(word,"add") == 0)
{
word = strtok(NULL, del);
temp = addNode(word);
if(head == NULL)
head = temp;
else
tail->next = temp;
tail = temp;
temp = head;
printf(" add:");
printf(" %s", temp->name);
temp = temp->next;
while(temp != NULL)
{
printf(", %s", temp->name);
temp = temp->next;
}
printf("\n");
}
/******** REMOVE *********/
else if( strcmp(word,"remove") == 0)
{
printf("remove:");
if (head == NULL)
printf(" queue is empty");
else
{
removeNode(head);
}
printf("\n");
}
/******** FLUSH *********/
else if( strcmp(word,"flush") == 0)
{
if (head == NULL)
printf(" flush: queue is empty");
else
freeNodes( head );
printf("\n");
}
}
freeNodes( head );
}
struct node* addNode(char *word)
{
struct node* temp = malloc( sizeof(struct node) );
strcpy(temp->name, word);
temp->next = NULL;
return temp;
}
void freeNodes(struct node* head)
{
struct node* temp;
printf(" flushing queue");
while(head != NULL)
{
temp = head->next;
free(head);
head = temp;
}
}
void removeNode (struct node* head)
{
struct node* temp;
temp = head->next;
free(head);
head = temp;
printf(" %s", temp->name);
temp = temp->next;
while(temp != NULL)
{
printf(", %s", temp->name);
temp = temp->next;
}
}发布于 2016-07-27 11:21:05
问题出在你的removeNode()函数。
它改变了指针头的地址--在removeNode()中的本地地址--以及它之前所指向的节点的空闲内存,而主函数中的指针头不变。所以当你调用removeNode(head)时,main中的指针头仍然指向在removeNode()函数中被释放的内存,因此它在之后的命令中出错。
以下是一些解决方案:
将指针头定义为全局variable
struct node* removeNode(struct node* head){}
告诉我这有没有帮助。
https://stackoverflow.com/questions/38602656
复制相似问题