、建立三元组抽象数据类型定义的头文件,编程实现三元组的基本操作,输出任意三元组的最大值和最小值。
时间: 2023-04-19 19:04:23 浏览: 76
以下是三元组抽象数据类型定义的头文件:
```
typedef struct {
int first;
int second;
int third;
} Triplet;
void InitTriplet(Triplet *T, int v1, int v2, int v3);
void DestroyTriplet(Triplet *T);
void Get(Triplet T, int i, int *e);
void Put(Triplet *T, int i, int e);
int IsAscending(Triplet T);
int IsDescending(Triplet T);
void Max(Triplet T, int *e);
void Min(Triplet T, int *e);
```
以下是三元组的基本操作的实现:
```
void InitTriplet(Triplet *T, int v1, int v2, int v3) {
T->first = v1;
T->second = v2;
T->third = v3;
}
void DestroyTriplet(Triplet *T) {
// 三元组不需要销毁
}
void Get(Triplet T, int i, int *e) {
switch (i) {
case 1:
*e = T.first;
break;
case 2:
*e = T.second;
break;
case 3:
*e = T.third;
break;
default:
*e = 0;
break;
}
}
void Put(Triplet *T, int i, int e) {
switch (i) {
case 1:
T->first = e;
break;
case 2:
T->second = e;
break;
case 3:
T->third = e;
break;
default:
break;
}
}
int IsAscending(Triplet T) {
return T.first <= T.second && T.second <= T.third;
}
int IsDescending(Triplet T) {
return T.first >= T.second && T.second >= T.third;
}
void Max(Triplet T, int *e) {
*e = T.first;
if (T.second > *e) {
*e = T.second;
}
if (T.third > *e) {
*e = T.third;
}
}
void Min(Triplet T, int *e) {
*e = T.first;
if (T.second < *e) {
*e = T.second;
}
if (T.third < *e) {
*e = T.third;
}
}
```
以下是输出任意三元组的最大值和最小值的示例代码:
```
#include <stdio.h>
#include "triplet.h"
int main() {
Triplet T;
int max, min;
InitTriplet(&T, 3, 1, 5);
Max(T, &max);
Min(T, &min);
printf("Max: %d\n", max);
printf("Min: %d\n", min);
return 0;
}
```
输出结果:
```
Max: 5
Min: 1
```