一种方式链接列表和不需要的第一个元素AFRTER填充

One way linked list and unwanted first element afrter filling

本文关键字:不需要 第一个 元素 填充 AFRTER 列表 一种 链接 方式      更新时间:2023-10-16

我的一种方式链接列表有问题。它是在C中写的。

输入:

3

4 5 6

输出是

0 4 5 6

所以0是不需要的。我在做什么错,错误的传球列表?在add()函数中看起来"如果"未完成。但是为什么,因为传递列表为空。

IDEONE链接到代码

这是一些代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct ELEMENT{
    int dane;
    struct ELEMENT *next;
}LIST;
void Add(LIST *FIRST, int x){
    LIST *ptr=FIRST,*el;
    el=(LIST*)malloc(sizeof(LIST));
    el->dane=x;
    el->next=NULL;
    if(ptr==NULL){
            ptr=el;
    }else{
        while(ptr->next!=NULL){
            ptr=ptr->next;
        }
        ptr->next=el;
    }
}
void Show(LIST *FIRST){
    LIST *ptr=FIRST;
    while(ptr!=NULL){
        printf("%d ",ptr->dane);
        ptr=ptr->next;
    }
    while(ptr!=NULL){
        ptr=ptr->next;
        free(ptr);
    }
}
LIST *HEAD=NULL;
int main()
{
    int i,counter,data;
    printf("Give me some data: n");
    scanf("%d",&counter);
    for(i=0;i<counter;i++){
        scanf("%d",&data);
        Add(&HEAD,data);
    }
    printf("nMy items:");
    Show(&HEAD);
    return 0;
}

例如修复

void Add(LIST **FIRST, int x){
    LIST *ptr=*FIRST,*el;
    el=(LIST*)malloc(sizeof(LIST));
    el->dane=x;
    el->next=NULL;
    if(ptr==NULL){
            *FIRST=el;
    }else{
        while(ptr->next!=NULL){
            ptr=ptr->next;
        }
        ptr->next=el;
    }
}
void Show(LIST *FIRST){
    LIST *ptr=FIRST;
    while(ptr!=NULL){
        printf("%d ",ptr->dane);
        ptr=ptr->next;
    }
    ptr=FIRST;
    while(ptr!=NULL){
        LIST *tmp = ptr;
        ptr=ptr->next;
        free(tmp);
    }
}
LIST *HEAD=NULL;
int main()
{
    int i,counter,data;
    printf("Give me some data: n");
    scanf("%d",&counter);
    for(i=0;i<counter;i++){
        scanf("%d",&data);
        Add(&HEAD,data);
    }
    printf("nMy items:");
    Show(HEAD);
    return 0;
}
if(ptr==NULL){
   ptr=el;
}

您在这里遇到了问题,在这种情况下,您只会更改PTR,而首先保持不变,因此最终您除了返回后的内存泄漏外什么都不做。

要解决此问题,您可以返回指针,也可以通过地址传递指针。