0
我試圖編寫一個程序,該程序從excel文件導入數據並將名稱存儲在鏈接列表中。第一列包含一個命令{add,remove,flush},如果該命令是add,則第二列包含一個名稱。C89刪除鏈接列表
它將名稱添加到列表的末尾,從前面刪除名稱,並在刷新時從名稱中刪除整個列表。 Add檢測名稱是否已經包含(尚未寫入)flush和remove還檢測隊列是否爲空。
示例文件:
add dave
add mike
remove
add paul
flush
add steve
輸出示例:
add: dave
add: dave, mike
remove: mike
flushing queue
add: steve
我的問題是,我清空命令無法正常刪除列表。該代碼必須符合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;
}
}
只是一個評論:C是性能最好的語言,鏈表是由於緩存局部性而導致的性能最差的數據結構。你爲什麼要使用一種難以使用的語言,然後故意擊敗它的主要用例?如果您不關心性能,請使用Excel的VBA。 –
您能否定義「不正確刪除列表」?程序是否在不刪除任何東西的情況下退出,或者是刪除了一些還是隻是崩潰? –