【发布时间】:2014-02-17 17:57:13
【问题描述】:
我的单向链表有问题。它是用 C 语言编写的。
输入:
3
4 5 6
输出是
0 4 5 6
所以 0 是不需要的。我在做什么错,错误的通过名单?看起来在 Add() 函数中首先“如果”没有完成。但是为什么,因为传递列表是空的。
这里有一些代码:
#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;
}
【问题讨论】:
-
注意:
&HEAD类型为LIST**。 -
在 Add() 或 GDB 中添加日志并跟踪它,看看有什么问题。
标签: c++ c data-structures linked-list structure