c - 链接列表输入被覆盖

标签 c list linked-list

我的代码需要一些帮助来覆盖存储在链接列表中的先前输入。这个项目比我这里的项目大得多,但在解决这个问题之前我无法继续。因此,假设用户输入“ins mom”“ins爸爸”“ins bob”,如果他们执行命令“prl”,它将打印出“bob bob bob”。它得到的节点数是正确的,但最后输入的 ins 命令总是填充列表并覆盖以前的内容。我花了一段时间尝试修复它,但仍然无法弄清楚。有人可以帮助我吗?

struct node{
    char *symbol;
    int count;
    struct node *next;
};
int main(void){

    void insert_node(struct node**,struct node**,char*,int);
    void print_list(struct node*); 

    struct node *head,*tail;
    char command[MAX]; 
    char word[MAX];
    int i = 1;
    head = tail = NULL;

    printf("Command? ");
    scanf("%s",command);
    if((strcmp(command,"prl")==0))
    {
        printf("The list is empty.");
        printf("Command? ");
        scanf("%s",command);    
    }
    else{
        scanf("%s",word);
    }
    while((strcmp(command,"end") != 0))
    {  
        if((strcmp(command,"ins")== 0))
        {
            insert_node(&head,&tail,word,i);
        }
        printf("Command? ");
        scanf("%s",command);
        if((strcmp(command,"prl")==0))
        {
            print_list(head);
        }
        else{
            scanf("%s",word);
        }
    }
    return 0;
}
void insert_node(struct node**h,struct node**t,char w[],int c) //inserts string into the list
{
    struct node *temp;

    if((temp = (struct node *)malloc(sizeof(struct node))) == NULL){
        printf("Node allocation failed. \n");
        exit(1);
    }
    temp->count = c;
    temp->symbol = w;
    temp->next = NULL; //edited this in

    if(*h == NULL)
    {
        *h = *t = temp;

    }
    else{
        (*t)->next = temp;  *t = (*t)->next;
    }
}
void print_list(struct node *h){ //prints the list

    if(h == NULL){
        printf("The list is empty.\n");
    }
    else{
        while(h != NULL)
        {
            printf("%d %s\n",h->count,h->symbol);
            h = h->next;
        }
    }
}

最佳答案

首先,您应该意识到留出空间:

temp->symbol

而不仅仅是使用一个简单的等式将一个字符串插入另一个等式中。使用:

strcpy()

在为字符串分配内存之后。

其次,在打印函数中,应该打印除最后一个节点之外的所有节点,因为 while 循环将被终止。更好地检查你的代码,你会没事的:)

关于c - 链接列表输入被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700238/

相关文章:

c# - 使用 dapper.NET C# 插入列表

c - 为什么我的链表打印倒着?

C++模板化链表问题

c - C 中的日期格式

c++ - 如何根据不同的扬声器分离音频文件

c++ - 返回链表中的最大值

python - 在列表的同一子列表中搜索多个元素

data-structures - LinkedList 不提供基于索引的访问,那么为什么它有 get(index) 方法?

C:将数学表达式字符串转换为 int 及其结果

c - 在给定 n 个点的平面中找到正方形