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;
    }
} 
4

3 回答 3

1

addhead分配后不会成功添加任何内容。它只更新一个本地current指针。您可以通过将搜索列表尾部的代码更改为

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

如果这没有帮助,您能否更新您的问题以显示如何add调用?(为了排除同一个char数组被用于多个调用的可能性,让所有nodes 的item指针指向同一个缓冲区。

此外,我看不到检查重复项的代码。您可以通过迭代列表来add在已经存在的分支中实现这一点,使用比较每个节点的.headstrcmpitemval

于 2013-10-16T16:22:58.403 回答
1

你的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;
    }        
}
于 2013-10-16T16:53:54.887 回答
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);
      }
}
于 2013-10-16T19:23:12.893 回答