九江市历届人大主任:一道C语言题,单链

来源:百度文库 编辑:神马品牌网 时间:2024/05/01 01:03:53
#include"stdlib.h"
#include"malloc.h"
struct node
{ int num;
char str[20];`
struct node *next;
};
void main()
{ struct node *create();
struct node *insert();
struct node *delet();
void printf();
struct node *head;
char str[20];
int n;
head=NULL;
head=create(head); /*create an empty struct table*/
printf(head); /*print struct table*/

printf("\n input inserted num,name:\n");
/*insert a student's infomation*/
gets(str); /*write the NO.*/
n=atoi(str); /*change the text NO. to int number*/
gets(str); /*write the name*/
head=insert(head,str,n); /*insert the node to struct*/
printf(head); /*print struct table under inster*/

printf("\n input deleted name:\n");
gets(str);
head=delet(head,str);
printf(head);
return;
}

/*********************create struct**********************/
struct node *create(struct node *head)
{ char temp[30];
struct node *p1,*p2;
p1=p2=(struct node*)malloc(sizeof(struct node));
printf("input num,name:\n");
printf("exit:double times enter!\n");
gets(temp);
gets(p1->str);
p1->num=atoi(temp);
p1->next=NULL;
while(strlen(p1->str)>0); /*when no name had write,end it*/
{ if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct node *)malloc(sizeof(struct node));
printf("input num,naem:\n");
printf("exit:double times enter!\n");
gets(temp);
gets(p1->str);
p1->num=atoi(temp);
p1->next=NULL;
}
return head;
}
就是上面的那一段create调用函数运行不下去了,死循环?
/***********************insert node****************************/
struct node *insert(struct node *head,char *Pstr,int n)
{ struct node *p1,*p2,*p3;
p1=(struct node *)malloc(sizeof(struct node));
strcpy(p1->str,Pstr);
p1->num=n;
p2=head;
if(head==NULL)
{ head=p1; p1->next=NULL; }
else
{ while(n>p2->num&&p2->next!=NULL)
{ p3=p2;
p2=p2->next;
}
if(n<=p2->num)
if(head==p2)
{ head=p1;
p1->next=p2;
}
else
{ p3->next=p1;
p1->next=p2;
}
else
{ p2->next=p1;
p1->next=NULL;
}
}
return(head);
}

还有:
/************************delete node**************************************/
struct node *delet(struct node *head,char *Pstr)
{ struct node *temp,*p;
temp=head;
if(head==NULL)
printf("\nList is null");
else
{ temp=head;
while(strcmp(temp->str,Pstr)!=0&&temp->next!=NULL)
{ p=temp;
temp=temp->next;
}
if(strcmp(temp->str,Pstr)==0)
if(temp==head)
{ head=head->next;
free(temp);
}
else
{ p->next=temp->next;
printf("delete string:%s\n",temp->str);
free(temp);
}
else printf("\nno find string!\n");
}
return(head);
}
/********************print every struct node*****************************/
void print(struct node *head)
{ struct node *temp;
temp=head;
printf("\n out put string:\n");
while(temp!=NULL)
{ printf("\n%d------%s\n",temp->num,temp->str);
temp=temp->next;
}
return;
}