与线性表类似,栈也有两种存储结构,即顺序存储和链表存储结构。
栈的顺序存储结构是利用一批地址连续的存储单元依次存放自栈底到栈顶的数据元素,同时设指针 top 指向栈顶元素的当前位置。
通常用一维数组来实现栈的顺序存储,习惯上以数组下标小的一端做栈底,当 top = 0 时为空栈,数据元素不断进栈时,栈顶指针 top 不断加 1,当 top 达到数组最大下标值时为栈满
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
| #include <iostream> #include<iomanip> using namespace std;
typedef int ElemType; const int MAXSIZE = 100; class CSqStack { private: ElemType elem[MAXSIZE]; int top; public: CSqStack() { top = 0; } ~CSqStack() {} void SetEmpty() { top = 0; } int IsEmpty(); void push(ElemType e); ElemType pop(); void PrintOut(); ElemType GetPop(); };
int CSqStack::IsEmpty() { if (top == 0) return 1; else return 0; }
void CSqStack::push(ElemType e) { if (top == MAXSIZE - 1) cout << "\n栈满溢出!" << endl; else { top++; elem[top] = e; } }
ElemType CSqStack::pop() { ElemType x = 0; if (top == 0) { cout << "\n栈为空,不能执行出栈操作!" << endl; } else { x = elem[top]; top--; } return x; }
ElemType CSqStack::GetPop() { ElemType x; if (top == 0) { cout << "已是空栈!\n"; x = -1; } else x = elem[top]; return x; }
void CSqStack::PrintOut() { cout << "PrintOut Data:"; if (top == 0) cout << "已是空栈!\n"; else { for (int k = top; k >= 1; k--) cout << setw(6) << elem[k]; cout << endl; } } int main() { ElemType x; CSqStack CStack;
CStack.push(1); CStack.push(2); CStack.push(3); CStack.push(4); CStack.push(5); x = CStack.GetPop(); cout << x << endl; CStack.PrintOut();
CStack.pop(); CStack.pop(); CStack.pop(); CStack.pop(); x = CStack.GetPop(); cout << x << endl; CStack.PrintOut(); return 0; }
|