一种方式链接列表和不需要的第一个元素AFRTER填充
One way linked list and unwanted first element afrter filling
我的一种方式链接列表有问题。它是在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,而首先保持不变,因此最终您除了返回后的内存泄漏外什么都不做。
要解决此问题,您可以返回指针,也可以通过地址传递指针。
相关文章:
- 为什么转换函数声明不需要至少一个定义类型说明符
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 是否可以使用另一个lua文件中定义的表,该表在当前文件中不需要作为模块
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 我需要做一个空函数循环回来,而不会让它崩溃或跳过
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- 为什么在一个地方需要双倍英镑,而在这个宏观上不需要其他地方?
- 我不明白我的错误需要返回一个指针数组
- 在我的第一个C++程序中需要一些帮助(简单)
- 我写了一个自定义的咖啡层.但是在训练期间,它说“**层不需要向后计算”
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 将参数初始化为构造函数,而不是第一个
- 缓冲区用不需要的数据填充 char 数组中的最后一个空格
- 插入排序与插入/擦除?(所以我需要对一个向量进行排序,而不是手工做事,而是使用插入和擦除
- 反转矢量项而不是第一个?C++
- 选择排序不排序第一个值
- 如何输出x=y^x, y=x而不需要另一个变量