#include <stdio.h>
#include <stdlib.h>
struct LNode{
int data;
LNode *next;
}*List,LNode;
void CreatList(List &L, int n){//创建一个含有n个元素的单链表
List p;
L=(List)malloc(sizeof(struct LNode));
L->next=NULL;//创建头节点
for(int i=1;i<=n;i++){
p=(List)malloc(sizeof(struct LNode));
scanf("%d",&p->data );
p->next=L->next;
L->next=p;//尾部插入法
}
}
void Traverse(List L2){
while(L2){
L2=L2->next;
printf("%d",L2->data );
}
}
int main(){
List L1;
int a;
printf("请输入元素的个数:");
scanf("%d",&a);
CreatList(L1,a);
Traverse(L1);
return 0;
}
这是最初的代码,编译不出来,出现下边的提示:
- [Error] variable or field ‘CreatList’ declared void
- [Error] ‘L’ was not declared in this scope
- [Error] expected primary-expression before ‘int’
经过一番分析,终于找到了错误之处,下边是正确的代码
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
LNode *next;
}*List,LNode;
void CreatList(List &L, int n){//创建一个含有n个元素的单链表
List p;
L=(List)malloc(sizeof(struct LNode));
L->next=NULL;//创建头节点
for(int i=1;i<=n;i++){
p=(List)malloc(sizeof(struct LNode));
scanf("%d",&p->data );
p->next=L->next;
L->next=p;//尾部插入法
}
}
void Traverse(List L2){
while(L2){
L2=L2->next;
printf("%d",L2->data );
}
}
int main(){
List L1;
int a;
printf("请输入元素的个数:");
scanf("%d",&a);
CreatList(L1,a);
Traverse(L1);
return 0;
}
改进的办法就是把定义链表的语句改为:
typedef struct LNode{
int data;
LNode *next;
}*List,LNode;
而第一个代码却是:
struct LNode{
int data;
LNode *next;
}*List,LNode