|
|
发表于 2012-3-24 18:34:38
|
显示全部楼层
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student *creat(void); //创建链表
void print(struct student *p); // 打印链表
struct student *dele(struct student *head); //删除链表
struct student *insert(struct student *head); // 插入链表
void command(struct student *head); //用于输入操作指令
struct student //定义结构体
{
int number;
char name[10];
long telephone;
struct student *next;
};
void main()
{
struct student * head;
printf("欢迎使用XX学校个人信息录入系统!\n");
head=creat();
print(head);
command(head);
printf("\n请退出系统!\n");
}
struct student *creat(void) // 创建链表
{
struct student *head, *p1;
int n=0;
head = (struct student*)malloc(sizeof(struct student));
struct student * pTail = head;
pTail->next = NULL;
p1 = (struct student*)malloc(sizeof(struct student));
printf("\n学号:");
scanf("%d",&(p1->number));
printf("姓名:");
scanf("%s",&(p1->name));
printf("电话号码:");
scanf("%ld",&(p1->telephone));
while(p1->number!=0)
{
pTail->next = p1;
pTail = p1;
p1->next = NULL;
p1=(struct student *)malloc(sizeof(struct student));
printf("\n学号:");
scanf("%d", &(p1->number));
printf("姓名:");
scanf("%s", &(p1->name));
printf("电话号码:");
scanf("%ld", &(p1->telephone));
}
pTail->next=NULL;
return head;
}
void print(struct student *p) //打印链表
{
p = p->next; //p指向了首节点
if (p == NULL)
{
printf("空链表!\n");
return ;
}
printf("\n学号\t\t姓名\t\t电话号码");
do
{
printf("\n%d\t\t%s\t\t%ld",p->number,p->name,p->telephone);
p=p->next;
}
while(p!=NULL);
}
struct student *dele(struct student *head) // 通过输入学号实现对链表数据的删除
{
int x;
printf("\n请输入要删除的学号:");
scanf("%d",&x);
struct student *p1,*p2;
if(head==NULL)
{
printf("nolist!");
exit(-1);
}
p1=head->next;
p2 = head;
while(p1->number!=x)
{
if(p1->next==NULL)
{
printf("找不到对应学号!");
return head;
}
p2 = p1; //记录p1的前一个节点
p1=p1->next;
}
p2->next = p2->next->next;
free(p1); //p1是要删除的节点
return head;
}
struct student *insert(struct student *head) // 通过输入学号实现对链表数据的插入(学号按升序)
{
printf("\n请输入要插入的学号:");
struct student *p0, *p1, *p2;
p0=(struct student *)malloc(sizeof(struct student));
p1=head;
scanf("%d",&p0->number);
printf("姓名:");
scanf("%s", &(p0->name));
printf("电话号码:");
scanf("%ld", &(p0->telephone));
while (p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
if (p0->number < p1->number)
{
p0->next = p2->next;
p2->next = p0;
return head;
}
}
p1->next = p0;
p0->next = NULL;
return head;
}
void command(struct student *head)
{
char instruction[10];
printf("\n请输入操作指令:"); //输入操作指令,控制插入和删除
scanf("%s",&instruction);
if(strcmp(instruction,"delete")==0)
{
head=dele(head); //调用删除函数
// printf("删除的元素:%d %s %ld", val.name, val.);
print(head);
command(head);
}
else if(strcmp(instruction,"insert")==0)
{
head=insert(head); //调用插入函数
print(head);
command(head);
}
else if(strcmp(instruction,"stop")==0)
return;
else
{
printf("\n无效指令!请重新输入!\n");
command(head);
}
}
|
|