本人学生,写的这段代码不能正常执行,在输入完单链表之后就无法正常进行下去,求大佬指点。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct List
{
int num;
char name[20];
struct List *next;
};
struct List * H_creat_list()
{
struct List *head,*p;
head=NULL;
p=(struct List*)malloc(sizeof(struct List));
scanf("%d%s",&p->num,p->name);
while(p->num!=-999)
{
p->next=head;
head=p;
p=(struct List*)malloc(sizeof(struct List));
scanf("%d%s",&p->num,p->name);
}
return head;
}
struct List *T_creat_list()
{
struct List *head,*p,*rear;
head=rear=NULL;
p=(struct List*)malloc(sizeof(struct List));
head=p;
scanf("%d%s",&p->num,p->name);
while(p->num!=-999)
{
rear=p;
p=(struct List*)malloc(sizeof(struct List));
rear->next=p;
scanf("%d%s",&p->num,p->name);
}
p->next=NULL;
return head;
}
void print(struct List *head)
{
struct List *p;
p=head;
while(p!=NULL)
{
printf("%d %.2f",p->num,p->name);
p=p->next;
}
printf("\n");
}
struct List *insert_Node_x(struct List *head, int num,char name[] )
{
struct List *p,*q,*s;
p=head;
q=NULL;
s=(struct List*)malloc(sizeof(struct List));
s->num=num;
strcpy(s->name,name);
if (head==NULL)
{
head=s; s->next=NULL;
}
else
{
while ((p!=NULL)&&(p->num<s->num))
{ q=p; p=p->next; }
if (p==head)
{ s->next=p; head=s; }
else
{ s->next=p; q->next=s;}
}
return head;
}
struct List *insert_Node_k(struct List *head, int num ,char name[],int k)
{
struct List *p,*s;
int i;
if(k<1) { printf("插入位置不合法\n"); exit(1);}
s=(struct List*)malloc(sizeof(struct List));
s->num=num;
strcpy(s->name,name);
p=head;
i=1;
if(k==1)
{ s->next=p; head=s; }
else
{ while ((p!=NULL)&&(i<k-1))
{ p=p->next; i++ ; }
if(p!=NULL)
{ s->next=p+1; p->next=s;}
else
{ printf("插入位置不合法\n"); free(s); exit(1); }
}
return head;
}
struct List *Del_Node_x(struct List *head,int x)
{
struct List *p,*q;
int found=0;
p=head; q=NULL;
while(p!=NULL)
{
if(p->num==x)
{ found=1;
break;
}
else
{ q=p;
p=p->next;
} }
if(found==1)
{ if(p==head)
head=p->next;
else
q->next=p->next;
free(p);
}
else
printf ("Node not found!");
return (head);
}
struct List *Del_Node_k(struct List *head,int k)
{
struct List *p;
int i;
if(k<1) { printf("删除位置不合法\n"); exit(1);}
p=head;
i=1;
if(k==1)
{ head=p->next;
free(p);
}
else
{ while ((p!=NULL)&&(i<k-1))
{ p=p->next; i++ ; }
if(p!=NULL)
{p->next=(p+1)->next;
free(p+1);
}
else
{ printf("插入位置不合法\n");exit(1); }
}
return head ;
}
int main()
{
struct List *p,*s;
int i,k,x;
printf("从键盘输入数据创建单链表,-999结束输入:\n");
s=H_creat_list();
printf("创建的单链表如下:\n");
print(s);
printf("输入k,x的值:");
scanf("%d%d",&k,&x);
printf("请输入你想调用函数的序号:");
scanf("%d",&i);
switch(i)
{
case 1:insert_Node_x(s,1001,"Zhang");break;
case 2:insert_Node_k(s,1001,"Zhang",k);break;
case 3:Del_Node_x(s,x);break;
case 4:Del_Node_k(s,k);break;
}
return 0;
}