这个程序是创建一个单向链表,输入“e”保存你输入的数,然后输入“L”可以查看你输入的数。
#include"stdlib。h"
#include"stdio。h"
//定义结构体,元素1为整数,元素2为指向下一个相同结构体的指针。
明显,会是个单向链表(如果你不知道单向链表最好先百度下,否则我的注释很可能你看不懂)。
struct node
{int n;
struct node *next;
};
struct node *head,*pt,*pn;//定义3个结构体指针,head为链表头指针,pt为操作指针,pn为插入的指针
void main()
{void pn_record(void);//函数声明
void listall(void);//函数声明
char ch;
int flag=1;
head=NULL;
while(flag)
{printf("
type 'E'or'e'to enter pn record,");
printf("type 'l'to list all records:");
ch=getchar();//输入一个字符赋给ch
getchar();//捕捉回车键(很有必要,否则程序以为键入第二个字符)
switch(ch)
{case 'e':
case 'E':pn_record();break;//输入e或E时执行函数pn_record()
case 'l':
case 'L':listall();break;//输入l或L时执行函数listall()
default:flag=0;//输入其他字符时退出程序
}/*end swich*/
}/*end while*/
}
//函数功能:向单项链表尾部插入一个从终端输入的数
void pn_record()
{
char numstr[5];
pn=(struct node*)malloc(sizeof(struct node));//分配空间
if (head==NULL)
head=pn;//若链表头为空,则把将要插入的数的结构体作为链表头
else
{//连表头不为空时
pt=head;//pt指向表头
while (pt->next!=NULL)
pt=pt->next;//遍历链表,直到pt指向链表尾部
//pt->next=pn;//这里写错了,应该放在下面
}
pt->next=pn;//------------放这里!!!
pt=pn;//pt指向将要插入的数的结构体
printf("
enter number:");
gets(numstr);
pt->n=atol(numstr);//将输入的数字字符串转化为数并写到pt指向的内存中,即pn中
pt->next=NULL;//pt指向的结构体的下一个地址为空,即pn指向的下一个地址为空(也就是链尾)
}
void listall(void)
{int i=0;
if (head==NULL)//链表头为空,则链表不存在(强烈建议main函数中将*head=NULL初始化!!否则这里可能会出错)
{printf("
empty list。
");
return;}
pt=head;//操作指针指向表头
do{
printf("
record number %d
", i);
printf("num:%ld
",pt->n);
pt=pt->next;//操作链表后移,即遍历整个表
}while (pt!=NULL);//直到指向表尾,则遍历结束
}
没注意head已经初始化过了,那句强烈建议你可以不看。
。。。。sorry
sorry。。。程序没错,,,我以为加了{}的是while。
全部