1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include<iostream> #include<string>
using namespace std;
#define MAXSIZE 10
typedef struct { int data[MAXSIZE]; int top1; int top2; }SqStack;
void InitStack(SqStack& S) { S.top1 = -1; S.top2 = MAXSIZE; }
bool StackEmpty(SqStack S) { if (S.top1 == -1 || S.top2 == MAXSIZE) { return true; } else { return false; } }
bool Push1(SqStack& S, int e) { if (S.top1 +1 == S.top2) { return false; } S.top1++; S.data[S.top1] = e; return true; }
bool Push2(SqStack& S, int e) { if (S.top1 + 1 == S.top2) { return false; } S.top2--; S.data[S.top2] = e; return true; }
bool Pop1(SqStack& S, int& e) { if (S.top1 == -1) { return false; } e = S.data[S.top1]; S.top1--; return true; }
bool Pop2(SqStack& S, int& e) { if (S.top2 == MAXSIZE) { return false; } e = S.data[S.top2]; S.top2++; return true; }
void GetTop1(SqStack S, int& e) { if (S.top1 == -1) { return; } e = S.data[S.top1]; }
void GetTop2(SqStack S, int& e) { if (S.top2 == MAXSIZE) { return; } e = S.data[S.top2]; }
int main() { SqStack S; InitStack(S); cout << "栈是否为空:" << StackEmpty(S) << endl; int a = 10; int b;
cout << "入1号栈:" << Push1(S, a) << endl; GetTop1(S, b); cout << "读取1号栈顶元素:" << b << endl; cout << "出1号栈:" << Pop1(S, a) << endl; cout << "栈是否为空:" << StackEmpty(S) << endl; cout << "入2号栈:" << Push2(S, a) << endl; GetTop2(S, b); cout << "读取2号栈顶元素:" << b << endl; cout << "出2号栈:" << Pop2(S, a) << endl; return 0; }
|