開始復習數據結構和算法,好長時間沒寫c了,順便復習一下
三元組的表示與實現
#include<iostream> #include <stdlib.h> 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; //定義一個三元組,初始化工作有InitTriplet函數進行 typedef ElemType * Triplet; //初始化函數 Status InitTriplet(Triplet &T, ElemType v1, ElemType v2, ElemType v3); //銷毀函數 Status DestroyTriplet(Triplet &T); //取得三元組的第i個元素賦值給e Status Get(Triplet T, int i, ElemType &e); //改變三元組的第i個元素的值為e Status Put(Triplet &T, int i, ElemType &e); //判斷三元組是否升序排列 1代表是 0代表不是 Status isAscending(Triplet T); //判斷三元組是否降序排列 1代表是 0代表不是 Status isDescending(Triplet T); //用e返回三元組中最大值 Status Max(Triplet T, ElemType &e); //用e返回三元組中最小值 Status Min(Triplet T, ElemType &e); //初始化函數 Status InitTriplet(Triplet &T, ElemType v1, ElemType v2, ElemType v3){ //給三元組分配空間 T = (ElemType *)malloc(3 * sizeof(ElemType)); //如果分配失敗,返回overFlow結果狀態 if (!T) exit(OVERFLOW); //給數組初初始化數值 T[0] = v1; T[1] = v2; T[2] = v3; //返回ok狀態 return OK; } //銷毀函數 Status DestroyTriplet(Triplet &T){ free(T); T = NULL; return OK; } //取得三元組的第i個元素賦值給e Status Get(Triplet T, int i, ElemType &e){ if (i<1 || i>3) return ERROR; e = T[i - 1]; return OK; } //改變三元組的第i個元素的值為e Status Put(Triplet &T, int i, ElemType &e){ if (i<1 || i>3) return ERROR; T[i - 1] = e; return OK; } //判斷三元組是否升序排列 1代表是 0代表不是 Status isAscending(Triplet T){ if (T[0] > T[1] && T[1] > T[2]){ return 1; }else{ return 0; } } //判斷三元組是否降序排列 1代表是 0代表不是 Status isDescending(Triplet T){ return (T[0] < T[1] && T[1] < T[2]); } //用e返回三元組中最大值 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; } //用e返回三元組中最小值 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; } void main(){ //定義一個三元組 Triplet triplet; //初始化三元組,元素分別是1,2,3 InitTriplet(triplet, 1,2,3); cout << triplet[0] << endl; int a; //將三元組的第2個元素賦值給a,所以a應該等於2 Get(triplet, 2, a); cout << a << endl; int b = 6; //將三元組的第三個元素改為6 Put(triplet, 1, b); cout << triplet[0] << endl; //應該返回0,因為三元組為6,2,3 cout << isAscending(triplet)<<endl; //也應該是 0 cout << isDescending(triplet) << endl; //最大值和最小值 int c; Max(triplet, c); int d; Min(triplet, d); cout << "最大值:"<<c <<"最小值"<< d << endl; }
運行結果