C语言数据结构-三元数组Triplet

#include <stdio.h>
#include<stdlib.h>

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

typedef int Status;

typedef int ElemType;
typedef int *Triplet;

Status InitTriplet(Triplet &T, ElemType v1, ElemType v2, ElemType v3){
    //操作结果:构造三元组T,元素e1,e2,e3分别赋值给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 DestoryTriplet(Triplet &T) {
    free(T);
    T = NULL;
    return OK;
}

Status Get(Triplet &T, int i, ElemType &e){
    if(i <1 || i > 3) {
        return ERROR;
    }

    e = T[i - 1];
    return OK;
}

Status Put(Triplet &T, int i, ElemType e) {
     if(i <1 || i > 3) {
        return ERROR;
    }

    T[i - 1] = e;
    return OK;
}

Status IsAscending(Triplet &T) {
    return (T[0] <= T[1]) && (T[1] <= T[2]);
}

Status IsDescending(Triplet &T) {
    return (T[0] >= T[1]) && (T[1] >= T[2]);
}

Status Max(Triplet T, ElemType &e) {
    e = (T[0] >= T[1])
        ? ((T[0] >= T[2]) ? T[0] : T[2])
        : ((T[1] >= T[2]) ? T[1] : T[2])
        ;
    return OK;
}

Status Min(Triplet T, ElemType &e) {
    e = (T[0] <= T[1])
        ? ((T[0] <= T[2]) ? T[0] : T[2])
        : ((T[1] <= T[2]) ? T[1] : T[2])
        ;
    return OK;
}

int main() {

	Triplet T;
	ElemType e, e1, e2, e3, r;
	e1 = 3;
	e2 = 5;
	e3 = 7;

	InitTriplet(T, e1, e2, e3);

    printf("====== e1 ========\n");
    Get(T, 1, e);
    printf("%-4d\n", e);
    printf("\n");

    printf("====== e2 ========\n");
    Get(T, 2, e);
    printf("%-4d\n", e);
    printf("\n");

    printf("====== e3 ========\n");
    Get(T, 3, e);
    printf("%-4d\n", e);
    printf("\n");

    e = 6;
    printf("====== put 6 e3 ========\n");
    Put(T, 3, e);
    printf("%-4d\n", e);
    printf("\n");

    printf("====== r = 1 ========\n");
    r = IsAscending(T);
    printf("%-4d\n", r);
    printf("\n");

    printf("====== r = 0 ========\n");
    r = IsDescending(T);
    printf("%-4d\n", r);
    printf("\n");

    printf("======  Max ========\n");
    Max(T, e);
    printf("%-4d\n", e);
    printf("\n");

    printf("======  Min ========\n");
    Min(T, e);
    printf("%-4d\n", e);
    printf("\n");

    DestoryTriplet(T);

    printf("====== T is null ? ========\n");
    if(T == NULL) {
        printf("t is null\n");
    } else {
        printf("t is not null\n");
    }

	return 0;
}

  

上一篇:数据结构学习笔记【第1章 绪论】


下一篇:334. Increasing Triplet Subsequence(也可以使用dp动态规划)