69,382
社区成员
发帖
与我相关
我的任务
分享
//仅供参考
//简单的按照楼主的思路修改了下,希望有所帮助(楼主想用的是单向链表吧)
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node
{
char name[20];
int num;
char sex[10];//考虑到中文字符男女性,所以改为数组
int age;
float score[10];
struct node *pNext;
};
struct node *g_pHead,*g_pTail;//全局指针类型变量,加了个g_p前缀,个人习惯,嘿嘿
void init_ht()
{
g_pHead=NULL;
g_pTail=NULL;
}
void destory_ht()//添加与init_ht()对应的销毁函数,释放资源,避免内存泄露
{
struct node* pTemp1=g_pHead;
while(pTemp1)
{
struct node* pTemp2=pTemp1->pNext;
free(pTemp1);
pTemp1=pTemp2;
}
g_pHead=NULL;
g_pTail=NULL;
}
void put(struct node *p)
{
if(p!=NULL)
{
if(g_pHead==NULL)
{
g_pHead=p;
}
if(g_pTail!=NULL)
{
g_pTail->pNext=p;//将上个尾节点的next指针指向当前节点
}
g_pTail=p;//更新尾节点
}
}
void print_node(struct node* p)//打印节点的函数
{
printf("\n%s\n","=========begin==========");//加个分割线
printf("name=%s\n",p->name);
printf("num=%d\n",p->num);
printf("sex=%s\n",p->sex);
printf("age=%d\n",p->age);
printf("scores=");
for(int i=0;i<10;i++)
{
printf("%f\t",p->score[i]);
}
printf("\n%s\n","=========end==========");//加个分割线
}
void input_data()
{
int i;
char ch;
struct node *p=NULL;
while(1)
{
fflush(stdin);
printf("input data(Y/N):");
scanf("%c",&ch);//这里将getch()改为scanf();不然会出问题
if(ch=='y'||ch=='Y')
{
p=(struct node *)(malloc(sizeof(struct node)));
memset(p,0,sizeof(struct node));//初始化p中属性,避免未知值
printf("input name:");
scanf("%s",&p->name);
printf("input num:");
scanf("%d",&p->num);
printf("input sex:");
scanf("%s",&p->sex);
printf("input age:");
scanf("%d",&p->age);
printf("input 10 score:");
for(i=0;i<10;i++)
{
scanf("%f",&p->score[i]);
}
put(p);
}
else
break;
}
}
void FDname()
{
char name[20];
struct node *p;
printf("input name:");
scanf("%s",name);
p=g_pHead;
int iCount=0;//统计计数
while(p!=NULL)
{
if(strcmp(name,p->name)==0)
{
++iCount;
print_node(p);
}
p=p->pNext;
}
if(iCount==0)
{
printf("没有该记录!\n");
}
}
void FDnum()
{
int i,num;
struct node *p;
printf("input num:");
scanf("%d",&num);
p=g_pHead;
int iCount=0;//统计计数
while(p!=NULL)
{
if(num==p->num)
{
++iCount;
print_node(p);
}
p=p->pNext;
}
if(iCount==0)
{
printf("没有该记录!\n");
}
}
void find_data()
{
char ch;
while(1)
{
fflush(stdin);//刷新输入缓冲,避免后续输入错误
printf("1:Find by name\n");
printf("2:Find by num\n");
printf("3:Exit\n");
scanf("%c",&ch);
switch(ch)
{
case '1':
FDname();
break;
case '2':
FDnum();
break;
case '3':
return;
}
}
}
void main()
{
init_ht();
input_data();
find_data();
destory_ht();
}