2013-10-16 50 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); 
     } 
}