#2
林月儿2015-05-28 15:59
初步改了下。。。能力有限。。。
#include"stdio.h" #include"stdlib.h" #define LEN sizeof(struct Student) typedef struct Student { long num; char name[20]; char sex[5]; int old; struct Student *next; }Student; int n=0; /*建立链表(不止一种方式)*/ Student *creat(void){ Student *head,*p;long num; p=head=(Student *)malloc(LEN); while(1){ p->next=(Student *)malloc(LEN); printf("输入第%d学生的信息(学号(学号为零就结束):",n+1);scanf("%ld",&num); if(num==0)break;p->num=num; printf("输入第%d学生的姓名:",n+1);scanf("%s",p->name); printf("输入第%d学生的性别(man or woman):",n+1);scanf("%s",p->sex); printf("输入第%d学生的年龄:",n+1);scanf("%d",&p->old); n++; p=p->next; } p=NULL; return head; } Student *del(Student *head,int old){ Student *p=head,*q;int c=0; while(c<n){ if(p->next->old==old){ q=p->next; p->next=q->next; } p=p->next;c++; } n--; return (head); } void print(Student *head){ Student *p=head;int cc=0; printf("\nnow these %d records are:\n",n); while(cc<n){ printf("%ld,%s,%s,%d\n",p->num,p->name,p->sex,p->old); p=p->next;cc++; } } int main(void){ int old; Student *head; head=creat(); printf("输入一个年龄:"); scanf("%d",&old); head=del(head,old); print(head); return 0; } |
#include"stdio.h"
#include"stdlib.h"
#define LEN sizeof(struct Student)
struct Student
{
long num;
char name[20];
char sex[5];
int old;
struct Student *next;
};
int n=0;
/*建立链表(不止一种方式)*/
struct Student *creat(void)
{
struct Student *head,*p1,*p2;
p1=p2=(struct Student *)malloc(LEN);
printf("输入第%d学生的信息(学号(学号为零就结束),姓名,性别(man or woman),年龄):\n",n+1);
scanf("%ld,%s,%s,%d",&p1->num,p1->name,p1->sex,&p1->old);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=malloc(LEN);
printf("输入第%d学生的信息(学号,姓名,性别(man or woman),年龄):\n",n+1);
scanf("%ld,%s,%s,%d",&p1->num,p1->name,p1->sex,&p1->old);
}
p2->next=NULL;
return head;
}
struct Student *del(struct Student *head,int old)
{
struct Student *p1,*p2;
int i=1;
p1=head;
while(i==1)
{
while((old!=p1->old)&&(p1->next!=NULL))
{
p2=p1;p1=p1->next;
}
if(old==p1->old)
{
if(p1==head)head=p1->next;
else p2->next=p1->next;
i=1;
}
else
{
printf("%d not been found!\n",old);i=0;
}
}
return (head);
}
void print(struct Student *head)
{
struct Student *p;
printf("\nnow these %d records are:\n",n);
p=head;
if(head!=NULL)
{
do
{
printf("%ld,%s,%s,%d",p->num,p->name,p->sex,p->old);
p=p->next;
}while(p!=NULL);
}
}
int main(void)
{
int old;
struct Student *head;
head=creat();
printf("输入一个年龄:");
scanf("%d",&old);
head=del(head,old);
print(head);
return 0;
}
为什么结果不正确啊??