我想添加到我的鏈接列表只有當我插入的項目不在鏈接列表中但當我嘗試遍歷它並打印出所有項目時正在打印出來。我似乎無法看到我做錯了什麼。任何幫助,將不勝感激插入項目到鏈接列表
// 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;
}
}
你是想故意比較字符串的指針,而不是字符串的內容? (即應該if(current-> item == val)'爲'if(strcmp(current-> item,val)== 0)'?)添加重複項時終止進程似乎相當嚴重;清理'new_node'然後返回看起來會更好。 – simonc
感謝您的更正@simonc。現在是否正確? –
它更好。如果添加了重複項,OP沒有指定行爲,所以我不能說調用'exit'是不正確的。我仍然認爲終止這個過程將會對預期的運行時狀況產生過度反應。我會讓'add'返回一個布爾值,並在這種情況下返回'false'來表示沒有添加任何內容。無論如何,因爲問題的主要錯誤是由您的答案修復的。 – simonc