【问题标题】:Why linked list head (current) keeps getting override by the new value?为什么链表头(当前)不断被新值覆盖?
【发布时间】:2022-12-16 01:11:57
【问题描述】:
while (tempcounter > 0){

        ticket *new=(ticket*)malloc(sizeof(ticket));
        ticket *old=*current;

        fscanf(f, "%s %s %s %s", temps, tempt, tempn, tempi);

        new->visitor.SrNo=temps;
        new->visitor.ticketNo=tempt;
        new->visitor.Name=tempn;
        new->visitor.ID=tempi;
        new->nextPtr=NULL;

        if (*current == NULL){
            *current=new;
            printf("sucess\n");
        } 
        else {
            while (old->nextPtr != NULL) {
                old = old->nextPtr;
            }    
            old->nextPtr = new;
        }
        tempcounter--;
    }

当从文件中读取时,第一个数据循环将被第二个数据循环覆盖,当我在另一个循环中打印当前头部时,它只会打印最后一个插入的元素。有谁知道为什么?

【问题讨论】:

标签: c file linked-list


【解决方案1】:

您的问题是,如果当前未更改,旧的将始终重置为当前。您需要将 current 重新分配给 old 或删除循环的第二行。因为在这里你在其他地方所做的就是将旧的最后一个设置为新的。然后当你重新启动时,while old 将重置为好像什么也没发生一样。 截至印刷。你要知道打印链表就是打印你的链表所在的元素。这是由于使用指针进行的迭代方法

这是您的代码问题的解决方案。

while (tempcounter > 0){
    ticket *new=(ticket*)malloc(sizeof(ticket));
    fscanf(f, "%s %s %s %s", temps, tempt, tempn, tempi);
    new->visitor.SrNo=temps;
    new->visitor.ticketNo=tempt;
    new->visitor.Name=tempn;
    new->visitor.ID=tempi;
    new->nextPtr=*current;
    *current = new
    printf("sucess
");
    tempcounter--;
}

要打印你可以做类似的事情

while (*current != NULL) {
    printf("%s ", current->visitor.SrNo);
    printf("%s ", current->visitor.ticketNo);
    printf("%s ", current->visitor.Name);
    printf("%s ", current->visitor.ID);
*current = current->next;
}

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多