将项目插入链接列表

时间:2013-10-16 16:21:03

标签: c

我正在尝试添加到我的链接列表,只有当我插入的项目不在链接列表中但是当我尝试遍历它并打印出所有项目时,没有任何内容正在打印出来。我似乎无法看到我做错了什么。任何帮助将不胜感激

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

3 个答案:

答案 0 :(得分:1)

add在分配head后无法成功添加任何内容。它只更新本地current指针。您可以通过将搜索列表尾部的代码更改为

来解决此问题
while (current->next != NULL) {
    current = current->next;
}
current->next = newNode;

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

此外,我没有看到检查重复项的代码。你可以在item已经存在add的分支内实现这一点,方法是使用head遍历列表,将每个节点strcmp与{{1}进行比较}。

答案 1 :(得分: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;
    }        
}

答案 2 :(得分: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);
      }
}