【DS】ADT_Triplet三元组的实现代码

代码
如下
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2

typedef int Status;
typedef int ElemType;

//采用动态分配的顺序存储结构
typedef ElemType *Triplet; 	//由InitTriplet分配3个元素存储空间

Status InitTriplet(Triplet &T, ElemType v1, ElemType v2, ElemType v3) {
	//构造三元组T,依次置T的3个元素初值为v1,v2,v3
	T = (ElemType *)malloc(3 * sizeof(ElemType));
	if(!T) exit(OVERFLOW);
	T[0] = v1;
	T[1] = v2;
	T[2] = v3;
	return OK; 
}//InitTriplet

Status DestroyTriplet(Triplet &T) {
	//销毁三元组
	free(T);	//先释放 
	T = NULL; 	//再让T指向NULL
	return OK; 
}//DestroyTriplet

Status Get(Triplet T, int i, ElemType &e) {
	//1 <= i <= 3,用e返回T的第i元的值
	if(i < 1 || i > 3) return ERROR;
	e = T[i - 1];
	return OK;
}//Get

Status Put(Triplet &T, int i, ElemType e) {
	//1 <= i <= 3,置T的第i元为e
	if(i < 1 || i > 3) return ERROR;
	T[i - 1] = e;
	return OK;
}//Put

Status IsAscending(Triplet T) {
	//如果T的3个元素按升序排列,则返回1,否则返回0
	return (T[0] <= T[1])&&(T[1] <= T[2]); 
}//IsAscending

Status IsDescending(Triplet T) {
	//如果T的3个元素按降序排列,则返回1,否则返回0
	return (T[0] >= T[1])&&(T[1] >= T[2]); 
}//IsDescending

Status Max(Triplet T, ElemType &e) {
	//用e返回指向T的最大元素的值
	e = (T[0] >= T[1]) ? ((T[0] >= T[2]) ? T[0] : T[2]) : ((T[1] >= T[2]) ? T[1] : T[2]);
	return OK; 
}//Max

Status Min(Triplet T, ElemType &e) {
	//用e返回指向T的最小元素的值
	e = (T[0] <= T[1]) ? ((T[0] <= T[2]) ? T[0] : T[2]) : ((T[1] <= T[2]) ? T[1] : T[2]);
	return OK; 
}//Min

int main() {
	Triplet T;
	
	cout << "InitTriplet..." << endl;
	int v1, v2, v3;
	cout << "input v1,v2,v3: ";
	cin >> v1 >> v2 >> v3;
	InitTriplet(T, v1, v2, v3);
	cout << "InitTriplet OK" << endl;
	puts("-");
	
	cout << "Get i..." << endl;
	int i, e;
	cout << "input i: ";
	cin >> i;
	Get(T, i, e);
	cout << "Get OK T[i] = " << e << endl;
	puts("-");
	
	cout << "Put i, e..." << endl;
	i = 0;
	e = 0;
	cout << "input i, e: ";
	cin >> i >> e;
	Put(T, i, e);
	Get(T, i, e);
	cout << "Put OK T[i] = " << e << endl;
	puts("-");
	
	cout << "IsAscending? : " << IsAscending(T) << endl;
	cout << "IsDescending? : " << IsDescending(T) << endl;
	e = 0; Max(T, e);
	cout << "Max : " << e << endl;
	e = 0; Min(T, e);
	cout << "Min : " << e << endl;
	
	return 0;
}
运行结果
如图:

在这里插入图片描述

发布了58 篇原创文章 · 获赞 72 · 访问量 6465
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览