2016-07-27 131 views
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; 
} 
} 
+0

只是一個評論:C是性能最好的語言,鏈表是由於緩存局部性而導致的性能最差的數據結構。你爲什麼要使用一種難以使用的語言,然後故意擊敗它的主要用例?如果您不關心性能,請使用Excel的VBA。 –

+0

您能否定義「不正確刪除列表」?程序是否在不刪除任何東西的情況下退出,或者是刪除了一些還是隻是崩潰? –

回答

0

問題是您的removeNode()函數。
它改變了指針頭的地址 - 本地在removeNode()中的地址 - 以及之前節點指針的空閒內存,而主函數中的指針頭沒有改變。所以當你打電話給removeNode(head)時,主指針頭仍然指向內存,在removeNode()函數中被釋放,所以後面的命令出錯了。
這些都是一些溶液:

  • 限定指針頭是全局變量
  • 功能的removeNode()應返回頭指針改變之後。像這樣:
    struct node* removeNode(struct node* head){}

告訴我,如果有幫助。