69,371
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
int num;
char name[20];
char sex;
int ages;
struct student *next;
};
int n;
struct student *creat()
{
struct student *head,*p1,*p2;
head = NULL;
p1 = p2 = (struct student *)malloc(LEN);
scanf("%d%s %c%d", &p1->num,p1->name,&p1->sex,&p1->ages);
while(p1->num!=0)
{
n=n+1;
if(n==1)
head = p1;
else
p2->next=p1;
p2 = p1;
p1 = (struct student *)malloc(LEN);
scanf("%d%s %c%d", &p1->num,p1->name,&p1->sex,&p1->ages);
}
free(p1); /* free not used node */
p2->next = NULL;
return(head);
}
struct student *cancel(struct student *phead)
{
int getage;
struct student *prev,*pcur;
scanf("%d", &getage);
if (phead->ages == getage) {
prev = phead;
phead = phead->next;
free(prev);
return phead;
}
prev = phead;
pcur = phead->next;
while (pcur) {
if (pcur->ages == getage) {
prev->next = pcur->next;
free(pcur);
return phead;
}
prev = pcur;
pcur = pcur->next;
}
return phead;
/*
while(p1!=0) //p1是p2前面的表头
{
if(p1->ages==getage)
{
if(head==p1)
head=p1->next;
else
p2->next=p1->next;
p1=p1->next;
}
else
{
p2=p1;
p1=p1->next;
}
}
*/
}
void print(struct student *phead)
{
struct student *p = phead;
while(p)
{
printf("%-5d %-8s %c %2d\n",p->num,p->name,p->sex,p->ages);
p = p->next;
}
}
//void main()
int main()
{
struct student *head;
head = creat();
print(head);
head = cancel(head);
print(head);
}
参考一下吧