我想添加到我的链接列表只有当我插入的项目不在链接列表中但当我尝试遍历它并打印出所有项目时正在打印出来。我似乎无法看到我做错了什么。任何帮助,将不胜感激插入项目到链接列表
// 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