网络部论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

链表例子 (插入学生信息 并全部显示)

向下

链表例子 (插入学生信息 并全部显示) Empty 链表例子 (插入学生信息 并全部显示)

帖子 由 Admin 周三 一月 21, 2009 5:41 pm

/* Note:Your choice is C IDE */
#include "stdio.h"
#include "stdlib.h"
struct stud
{
char name[20];
long num;
int age;
char ***;
float score;
struct stud *next;
};
void new_record();
void listAll();
struct stud *head,*cur,*newp;
void main()
{
char ch;
int flag=1;
head=NULL;
while(flag)
{
printf("\n type 'E' or 'e' to enter new record,");
printf("\n type 'L' or 'l' to list all records:");
ch=getchar();
getchar();
switch(ch)
{
case 'e':
case 'E':new_record();
break;
case 'l':
case 'L':listAll();
break;
default:flag=0;
};
}
}
void new_record(void)
{
char numstr[20];
newp=(struct stud *)malloc(sizeof(struct stud));
if(head==NULL)
{
head=newp;
}//初始化头指针 再次调用时不会运行
else
{
cur=head;
while(cur->next != NULL)
{
cur=cur->next;
}
cur->next=newp;
}
cur=newp;
//已经将newp结构插入,cur现在指向链的末端,即刚插入的节点,即要输入数据的地方
printf("\n enter name:");
gets(cur->name);
printf("\n enter number:");
gets(numstr);
cur->num=atol(numstr);
printf("\n enter age:");
gets(numstr);
cur->age=atoi(numstr);
printf("\n enter ***:");
cur->***=getchar();
getchar();
printf("\n enter score:");
gets(numstr);
cur->score=atof(numstr);
cur->next=NULL;
}
void listAll(void)
{
int i=0;
if(head==NULL)
{
printf("\n emputy list.\n");
return;
}
cur=head;
do
{
printf("\n record number %d\n",++i);
printf("name: %s\n",cur->name);
printf("num: %ld\n",cur->num);
printf("age: %d\n",cur->age);
printf("***: %c\n",cur->***);
printf("score: %6.2f\n",cur->score);
cur=cur->next;
}while(cur!=NULL);
}



运行结果


type 'E' or 'e' to enter new record,
type 'L' or 'l' to list all records:l
emputy list.
type 'E' or 'e' to enter new record,
type 'L' or 'l' to list all records:e
enter name:zy
enter number:200725068
enter age:20
enter ***:1
enter score:100
type 'E' or 'e' to enter new record,
type 'L' or 'l' to list all records:l
record number 1
name: zy
num: 200725068
age: 20
***: 1
score: 100.00
type 'E' or 'e' to enter new record,
type 'L' or 'l' to list all records:
Admin
Admin
Admin

帖子数 : 144
年龄 : 34
注册日期 : 08-03-09

http://www.gaozhong.blog.sohu.com

返回页首 向下

返回页首


 
您在这个论坛的权限:
不能在这个论坛回复主题