数据结构实验一:抽象数据类型Triplet的实现和表示;
实验代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OK 1
#define TRUE 1
#define ERROR 0
#define FALSE 0
#define OVERFLOW -2
#define INFEASIBLE -1
typedef int Status;
typedef Status ElemType;
typedef ElemType * Triplet;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
Status InitTriplet(Triplet &T,ElemType a1,ElemType a2,ElemType a3);
Status Get(Triplet T,int i,ElemType &e);
Status Put(Triplet T,int i,ElemType e);
Status IsAscending (Triplet T);
Status IsDescending (Triplet T);
Status Max(Triplet T,ElemType &e);
Status Min(Triplet T,ElemType &e);
Status DestroyTriplet(Triplet &T);
int main(int argc, char *argv[]) {
Triplet a;
Status b;
Status c;
Status d;
Status e;
Status f ;
if(InitTriplet(a,1,2,3)){
printf("请输入三元组某一元位置:");
scanf("%d",&b);
if(Get(a,b,c)){
printf("该元的值为:%d\n",c);
}else{
printf("输入有误;\n");
}
printf("\n");
printf("请输入要改变元的位置:");
scanf("%d",&d);
printf("输入要改变的数值:");
scanf("%d",&c);
if(Put(a,d,c)){
printf("改变后的该元的值:%d\n",a[d-1]);
}else{
printf("输入有误;\n");
}
if(IsAscending(a)){
printf("该三元组为升序排列;\n");
}else{
printf("该三元组不是升序排列;\n");
}
if(IsDescending (a)){
printf("该三元组为降序排列;\n");
}else{
printf("该三元组不是降序排列;\n");
}
if(Max(a,e)){
printf("该三元组的最大值是:%d\n",e);
}
if(Min(a,f)){
printf("该三元组的最小值是:%d\n",f);
}
if(DestroyTriplet(a)){
printf("该三元组已经销毁;");
}
}else{
printf("输入有误;");
}
return 0;
}
Status InitTriplet(Triplet &T,ElemType a1,ElemType a2,ElemType a3){ //初始化列表
T=(ElemType *)malloc(3*sizeof(ElemType));
if(T==0){
exit(OVERFLOW);
}else{
printf("动态内存申请成功;\n");
}
T[0]=a1;
T[1]=a2;
T[2]=a3;
return OK;
}
Status Get(Triplet T,int i,ElemType &e){ //功能:返回三元组的某一元
if(i>=1&&i<=3){
e=T[i-1];
return OK;
}else{
return ERROR;
}
}
Status Put(Triplet T,int i,ElemType e){ //功能:改变三元组某一元的值
if(i>=1&&i<=3){
T[i-1]=e;
return OK;
}else{
return ERROR;
}
}
Status IsAscending (Triplet T){ //判断函数升序排列
if(T[0]<=T[1]&&T[1]<=T[2]){
return OK;
} else{
return ERROR;
}
}
Status IsDescending (Triplet T){ //判断函数降序排列
if(T[0]>=T[1]&&T[1]>=T[2]){
return OK;
} else{
return ERROR;
}
}
Status Max(Triplet T,ElemType &e){ //寻找三元组的最大值
e=(T[0]>T[1])?T[0]:T[1];
if(e<T[2]){
e=T[2];
}
return OK;
}
Status Min(Triplet T,ElemType &e){ //寻找三元组的最小值
e=(T[0]<T[1])?T[0]:T[1];
if(e>T[2]){
e=T[2];
}
return OK;
}
Status DestroyTriplet(Triplet &T){
free(T);
T=NULL;
return OK;
}
运行结果:
第一次实验遇到的问题是:参数中的Triplet &T这是c++种的引用类型,即原类型的别名,与原类型代表同一变量,这里的引用符号&并不代表地址。
引用类型的数据存储在堆中,而内存单元只存放堆中的对象地址,声明引用不开辟内内存空间,在声明一个变量的引用后,在本函数执行期间,该引用不能再次作为其他变量的别名;