我的单向链表有问题。它是用 C 写的。
对于输入:
3
4 5 6
输出是
0 4 5 6
所以 0 是不需要的。我做错了什么,错误的通过列表?看起来在 Add() 函数中第一个“if”没有完成。但是为什么,因为传递的列表是空的。
这是一些代码:
#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;
}
关于c++ - 单向链表和填充后不需要的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21371652/