回复 楼主 chenxd
帮我看一道题可以吗大神。我第一个节点删不了,刚学有点不懂,求解决。第一个节点出现删除时,出现错误。求大神解决
题如下:
#include<stdio.h>
#include <stdlib.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
char name[10];
long no;
char tel[13];
char Email[20];
struct student *next;
};
struct student *head;
int n;
struct student *creat()
{
struct student *p,*q;
int i;
printf("学生人数:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p=(struct student *)malloc(LEN);
printf("姓名:"); scanf("%s",p->name);
printf("学号:"); scanf("%ld",&p->no);
printf("电话:"); scanf("%s",p->tel);
printf("邮箱:"); scanf("%s",p->Email);
if(i==0)
head=p;
else
q->next=p;
q=p;
}
q->next=NULL;
return(head);
}
void print(struct student *head)
{
struct student *p;
printf("\n\tname\t\tno\t\ttel\t\tEmail\n");
p=head;
if(p==NULL)
printf("链表为空");
else
{
while(p!=NULL)
{
printf("\t%s\t\t%d\t\t%s\t\t%s\n",p->name,p->no,p->tel,p->Email);
p=p->next;
}
}
}
void find(struct student *head)
{
int st;
struct student *p;
printf("输入学号:");
scanf("%ld",&st);
p=head;
while(p!=NULL&&p->no!=st)
p=p->next;
if(p!=NULL)
{
printf("\n\tname\tno\ttel\tEmail\n");
printf("\t%s\t%d\t%s\t%s\n",p->name,p->no,p->tel,p->Email);
}
else
printf("不存在%d学号的学生\n",st);
}
int del(struct student *head,int m)
{
struct student *p,*q;
q=head;
p=head->next;
while(p!=NULL)
if(m!=p->no)
{
q=q->next;
p=p->next;
}
else
break;
if(p==NULL)
return 0;
q->next=p->next;
free(p);
return 1;
}
void insert(struct student *head,int m)
{
struct student *p,*q,*k;
k=(struct student *)malloc(LEN);
k->no=m;
q=head;
p=head->next;
while(p!=NULL)
if(p->no<=m)
{
q=q->next;
p=p->next;
}
else
break;
k->next=p;
q->next=k;
n=n+1;
printf("请输入新学生的基本情况:\n");
printf("姓名:"); scanf("%s",k->name);
printf("学号:"); scanf("%ld",&k->no);
printf("电话:"); scanf("%s",k->tel);
printf("邮箱:"); scanf("%s",k->Email);
}
void main()
{
int k,m;
head=creat();
printf("链表为:");
print(head);
printf("寻找链表的节点为:");
find(head);
printf("输入插入节点的学号:");
print(head);
scanf("%d",&m);
insert(head,m);
print(head);
printf("输入删除节点的学号:");
scanf("%d",&m);
k=del(head,m);
if(k==1)
{
printf("删除节点后的链表为:");
print(head);
}
else
printf("需要删除的节点不存在");
}