链表删除问题,新手请教!
链表删除问题
建立一个链表,每个结点包括:学号, 姓名,性别,年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将该结点删除。
以下是代码:请大牛帮忙修改下,现在的主要问题是程序没办法输出删除后的数据,我想了很久还是找不出问题所在,借大牛慧眼帮忙看一下修改下。
#include<stdio.h>
#include<stdlib.h>
struct student
{
int number;
char name[30];
char sex;
int age;
struct student *next;
};
int main()
{
struct student *head,*p1,*p2;
p1=(struct student*)malloc(sizeof(struct student));
p2=(struct student*)malloc(sizeof(struct student));
int n,c_age;
head=p1;
scanf("%d",&n);//输入链表的长度n
while(n--)
{
scanf("%d%s%c%d",&p1->number,&p1->name,&p1->sex,&p1->age);//学号、姓名、性别、年龄
p1=p1->next;
p1=(struct student*)malloc(sizeof(struct student));
}
p1=head;
scanf("%d",&c_age);// 输入要删除的年龄
for(int i=0;i<n;i++) //寻找是否有与输入的年龄c_age相同的年龄,如果有,删除掉
{
p2->next=p1;
if(c_age==p1->age)
{
p2->next=p1->next;
}
p2=(struct student*)malloc(sizeof(struct student));
printf("%d %s %c %d\n",p2->next->number,p2->next->name,p2->next->sex,p2->next->age);//输出删除数据后的链表数据
p1=p1->next;
}
system("pause");
return 0;
}
范例:
Sample Input
4
101 Ma m 20
102 Li f 23
103 Zhang m 19
104 Wang m 19
19
Sample Output
101 Ma m 20
102 Li f 23
[解决办法]
分值太低了,结贴吧~~~
不是让你抄,而是通过阅读理解加以提高~~~
#include<stdio.h>#include<stdlib.h>struct student{ int number; char name[30]; char sex; int age; struct student *next;};int main(){ struct student head,*p1=&head,*p2; int n,c_age; scanf("%d",&n);//输入链表的长度n head.next=NULL; while(n-->0) { p1->next=(struct student*)malloc(sizeof(struct student)); p1=p1->next; p1->next=NULL; scanf("%d %s %c %d",&p1->number,p1->name,&p1->sex,&p1->age);//学号、姓名、性别、年龄 } printf("\n\n请输入要删除的年龄:"); scanf("%d",&c_age);// 输入要删除的年龄 printf("\n\n删除后的显示结果:\n"); p1=head.next; while(p1!=NULL) //寻找是否有与输入的年龄c_age相同的年龄,如果有,删除掉 { if(c_age!=p1->age) { printf("%5d %10s %5c %6d\n",p1->number,p1->name,p1->sex,p1->age);//输出删除数据后的链表数据 } p2=p1->next; free(p1); p1=p2; } return 0;}