对书中的Max(), Min(),Get()等函数原型有修改,直接返回ElemType而不是使用e接收值。
需要注意的是:数组默认以引用传递。
实现如下:
1. 头文件:
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define ELEM_NUM 3
/* data type */
typedef int ElemType;
typedef int Status;
typedef ElemType * Triplet;
/* init */
Status InitTriplet(Triplet* T, ElemType v1, ElemType v2, ElemType v3);
/* destory */
Status DestoryTriplet(Triplet T);
/* put the ith element's value to be e */
Status Put(Triplet T, int i, ElemType e);
/* get the ith element's value ,return by e */
ElemType Get(Triplet T, int i);
/* is it ascending? */
Status IsAscending(Triplet T);
/* is it desending? */
Status IsDscending(Triplet T);
/* <pre name="code" class="objc">return the max Element */
ElemType Max(Triplet T);
/* return the min Element */
ElemType Min(Triplet T);
void Print(Triplet T);
2. 实现。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "ds_1.7.h"
int main(){
ElemType e;
Triplet T;
InitTriplet(&T, 2, 8, 7);
Print(T);
e = Get(T, 1);
printf("the 1th elemt of T(Start from 1->3) is %d\n",e);
e = Get(T, 2);
printf("the 2th elemt of T(Start from 1->3) is %d\n",e);
e = Get(T, 3);
printf("the 3th elemt of T(Start from 1->3) is %d\n",e);
Put(T, 1, 10);
Put(T, 2, 5);
printf("%d - %d - %d\n",T[0], T[1], T[2]);
printf("the 2th elemt of T(Start from 1->3) is %d\n",Get(T, 1));
printf("is asc?, %d\n", IsAscending(T));
printf("is desc?, %d\n", IsDscending(T));
e = Max(T);
printf("the max elemt of T is %d\n",e);
e = Min(T);
printf("the min elemt of T is %d\n",e);
return 0;
}
Status InitTriplet( Triplet *T, ElemType v1, ElemType v2, ElemType v3 ){
*T = (ElemType *) malloc( 3 * sizeof(ElemType));
if( !T ){
exit(OVERFLOW);
}
(*T)[0] = v1;
(*T)[1] = v2;
(*T)[2] = v3;
return OK;
}
Status DestoryTriplet( Triplet T ){
free(T);
T = NULL;
return OK;
}
Status Put(Triplet T, int i, ElemType e){
if( i < 1 || i > ELEM_NUM ){
return ERROR;
}
T[i - 1] = e;
return OK;
}
ElemType Get( Triplet T, int i){
if( i < 1 || i > 3 ){
return ERROR;
}
ElemType e = T[ i - 1 ];
return e;
}
Status IsAscending( Triplet T ){
return (T[0] <= T[1] && T[1] <= T[2]);
}
Status IsDscending( Triplet T){
return (T[0] >= T[1] && T[1] >= T[2]);
}
ElemType Max( Triplet T){
ElemType m = T[0];
int i;
for(i = 1; i < ELEM_NUM; i++){
if(T[i] > m){
m = T[i];
}
}
return m;
}
ElemType Min( Triplet T){
ElemType m = T[0];
int i;
for(i = 1; i < ELEM_NUM; i++){
if(T[i] < m){
m = T[i];
}
}
return m;
}
void Print( Triplet T){
printf("%d - %d - %d\n",T[0], T[1], T[2]);
}