c双向循环链表求指导
#include<stdio.h>#include<stdlib.h>
struct student //结构体创建
{
char name[10];
int score;
struct student *prior;
struct student *next;
};
struct student *insert(struct student *head)
{
struct student *p,*pnew,*pold;
pnew=(struct student *)malloc(sizeof(struct student));
scanf("%s%d",pnew->name,&pnew->score);
p=head;
if(pnew->score>head->score){
pnew->next=head;
head->prior=pnew;
head=pnew;
}
else{
while(p!=NULL&&pnew->score<p->score){
}
pnew->next=p;
p->prior=pnew;
pold->next=pnew;
pnew->prior=pold;
}
return head;
}
struct student *create(int n)
{
struct student *head,*pnew,*ptail;
int i;
pnew=(struct student *)malloc(sizeof(struct student));
printf("请输入学生姓名及成绩\n");
scanf("%s%d",pnew->name,&pnew->score);
head=ptail=pnew; //建立头节点
for(i=1;i<n;i++){
printf("请输入学生姓名及成绩\n");
head=insert(head);
}
ptail->next=NULL;
return head;
}
void print1(struct student *head)
{
struct student *p=head;
while(p!=NULL){
printf("%s %f\n",p->name,p->score);
p=p->next;
}
}
void print2(struct student *head)
{
struct student *p=head;
while(p!=head){
printf("%s %f",p->name,p->score);
p=p->prior;
}
printf("%s %d\n",p->name,p->score);
}
struct student *pdelete(struct student *head,int grade)
{
struct student *p,*pold,*ptail;
p=head;
while(head!=NULL&&head->score>=grade){
head=head->next;
p=head->prior;
free(p);
p=head;
}
if(head==NULL) return head;
p=head->next;
pold=head;
ptail=p->next;
while(head!=NULL){
if(p->score>=grade){
pold->next=p->next;
pold=ptail->prior;
free(p);
p=pold->next;
}
else{
pold=p;
p=p->next;
ptail->prior=pold;
}
}
return head;
}
int destory(struct student *head)
{
struct student *p,*q;
while(p!=q)
{
p=head->prior;
q=head->next;
q->prior=q;
p->next=q;
free(head);
head=q;
}
return 6;
}
void main()
{
struct student *create(int n);
void print1(struct student *head);
void print2(struct student *head);
struct student *insert(struct student *head);
struct student *pdelete(struct student *head,int grade);
int destory(struct student *head); //函数声明
int j,k=0,m,n;
struct student *head;
printf("请输入要建立节点的个数:\n");
scanf("%d",&n);
create(n); //建立一链表并使其按成绩从高到地排列
printf("请选择要进行的操作:\n1.插入;\n2.删除;\n3.正向遍历输出;\n4.反向遍历输出;\n5.销毁\n");
scanf("%d",&m);
while(k!=6){
switch(m){
case 1: printf("请输入要插入的学生姓名及成绩:\n");
head=insert(head);
print1(head);
break;
case 2: printf("请输入及格线"); //删除已经及格的学生
scanf("%d",&j);
head=pdelete(head,j);
print1(head);
break;
case 3:print1(head); //正向遍历输出
break;
case 4:print2(head); //反向遍历输出
break;
case 5:k=destory(head); //销毁
break;
}
}
}