2013-10-16 131 views
1

我想添加到我的鏈接列表只有當我插入的項目不在鏈接列表中但當我嘗試遍歷它並打印出所有項目時正在打印出來。我似乎無法看到我做錯了什麼。任何幫助,將不勝感激插入項目到鏈接列表

// my add function 
void add(char *val) 
{  
    printf("%s", val);// val is getting printed so i know its being passed in. 
    if(head == NULL){ 
     struct node *new_node = (struct node *)malloc(sizeof(struct node)); 
     head = new_node; 
     head->item = val; 
     head->next = NULL; 
    } else{ 
     struct node *current = head; 
     struct node *newNode = (struct node *) malloc(sizeof(struct node)); 
     if (newNode == NULL) { 
      exit(-1); 
     }   
     newNode->item = val; 
     newNode->next = NULL; 

     while (current != NULL) { 
      current = current->next; 
     }  
     current = newNode; 
    } 
} 

//my traverse function 
void goThroughList() { 
    struct node *current = head; 
    while(current != NULL){ 
     printf("%s\n",current->item); 
     current= current->next; 
    } 
} 

回答

1

add一旦head已分配未成功添加任何東西。它只更新本地的current指針。你可以解決這個問題通過更改爲表尾搜索到

while (current->next != NULL) { 
    current = current->next; 
} 
current->next = newNode; 

如果這沒有幫助的代碼,您可以更新您的問題,以顯示add是如何被叫什麼名字? (爲了排除同一char陣列被用於多個呼叫,留下所有node s的其item指針指向相同的緩衝液的可能性。

此外,不存在代碼我可以看到,對於重複檢查。您可以實現這其中head已經通過strcmp來比較每個節點的用itemval

1

add功能通過列表迭代存在的add分支內是不正確

試試這個:

void add(char *val) 
{  
    printf("%s", val);// val is getting printed so i know its being passed in. 

    if(head == NULL){  
     struct node *new_node = (struct node *)malloc(sizeof(struct node)); 
     new_node->item = val; 
     new_node->next = NULL; 
     head = new_node; 
    } 
    else{ 
     struct node *current = head; 
     while (current->next != NULL) { 
     if(strcmp(current->item, val) == 0) 
      return; 
     current = current->next; 
     } 
     struct node *new_node = (struct node *)malloc(sizeof(struct node)); 
     new_node->item = val; 
     new_node->next = NULL; 
     current->next = new_node; 
    }   
} 
+0

你是想故意比較字符串的指針,而不是字符串的內容? (即應該if(current-> item == val)'爲'if(strcmp(current-> item,val)== 0)'?)添加重複項時終止進程似乎相當嚴重;清理'new_node'然後返回看起來會更好。 – simonc

+0

感謝您的更正@simonc。現在是否正確? –

+0

它更好。如果添加了重複項,OP沒有指定行爲,所以我不能說調用'exit'是不正確的。我仍然認爲終止這個過程將會對預期的運行時狀況產生過度反應。我會讓'add'返回一個布爾值,並在這種情況下返回'false'來表示沒有添加任何內容。無論如何,因爲問題的主要錯誤是由您的答案修復的。 – simonc

0

這個函數是幹什麼的?

void goThroughList() { 
    struct node *current = head; 
    while(current != NULL){ 
     printf("%s\n",current->item); 
     current= current->next; 
    } 
} 

試試這個:

void goThroughList(struct node* llist) 
{ 
     if(llist) 
     { 
     printf("%s" , llist->item); 
      goThroughList(llist->next); 
     } 
}