数据结构的简单学习4

这次我采用了顺序表的数据结构,在可操作性方面,要比单纯用数组存储数据要好的多。

把个人信息给分离出来单独建一个结构体。

 

#include<stdio.h>
#include<string.h>
#include<malloc.h>

#define MaxSize 10
#define MaxNumber  100

typedef struct
{
	char name[MaxSize];			//姓名
	unsigned int age;			//年龄
	//......
}Information;					//个人信息结构体

typedef struct
{
	Information InfNumber[MaxNumber];//信息  (顺序表)
	int Length;						 //表中已经存在的结点的个数	
}People;


void main()
{
	int number;
	int i;
	People stu;						//定义一张“顺序表”,存放数据
	//初始化顺序表的长度为0
	stu.Length = 0;
	
	printf("Please enter the number of student(under 100):\n");
	scanf("%d",&number);
	
	for(stu.Length=0;stu.Length<number;stu.Length++)
	{
		printf("Please enter the following information(name,years):\n ");
		scanf("%s %d",stu.InfNumber[stu.Length].name,
			&stu.InfNumber[stu.Length].age);
		getchar();
	}
	
	for(i=0;i<stu.Length;i++)
	{
		printf("Name=%s,Age=%d\n",stu.InfNumber[i].name,
			stu.InfNumber[i].age);
	}

	printf("%d个学生\n",stu.Length);
	
}


但上面写的代码,可读性不高,就看这个stu.InfNumber[stu.Length].name 就够让人头疼的了。

接下来怎么改呢?

#include<stdio.h>
#include<string.h>
#include<malloc.h>

#define MaxSize 10
#define MaxNumber  100

typedef struct
{
	char name[MaxSize];			//姓名
	unsigned int age;			//年龄
	//......
}Information;					//个人信息结构体

typedef struct
{
	Information InfNumber[MaxNumber];//信息  (顺序表)
	int Length;						 //表中已经存在的结点的个数	
}People;

int stuAdd(People *stu,Information *inf);
int stuOutput(People *stu);
void main()
{
	People stu;						//定义一张“顺序表”,存放数据
	Information *tempINF;
	tempINF=(Information*)malloc(sizeof(Information));//分配内存
	//初始化顺序表的长度为0
	stu.Length = 0;

	do
	{
		printf("Please enter the following information(name,years):\n ");
		scanf("%s %d",tempINF->name,&tempINF->age);
		if(tempINF->age > 0)						
		{
			if(-1 == stuAdd(&stu,tempINF))
			{
				break;
			}
		}else{
			break;									//如果年龄为0,则退出循环
		}
		
	}while(1);
	stuOutput(&stu);
	
	printf("%d\n",stu.Length);
	free(tempINF);				//释放内存
}

int stuAdd(People *stu,Information *inf)
{
	if((stu->Length) >= MaxSize)		//顺序表满了
	{
		printf("顺序表满了,不能再添加信息了\n");
		return -1;			//添加失败
	}
	stu->InfNumber[stu->Length]=*inf;
	++stu->Length;						//长度加1
		
	return 0;			//添加成功
}
int stuOutput(People *stu)
{
	int index;
	for(index=0;index< (stu->Length);index++)
	{
		printf("%s %d\n",stu->InfNumber[index].name,stu->InfNumber[index].age);
	}
	return 0;
}


新的问题又来了,代码太长了,放在一个文件里边,看着乱七八糟的。

应该划分一下了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值