9.22学习总结
(1)题目要求:将编号0和1两个栈存放于一个数组空间V[m]中,栈底分别位于数组的两端。当0号栈的栈顶指针top[0] = -1时该栈为空,当1号栈的栈顶指针top[1]等于m时,该栈为空。两个栈均从两端向中间增长。
(2)源代码
#include <iostream> #include <string> #include <iomanip> using namespace std; class SElemType { public: int data; SElemType(int data=0): data(data) {} }; typedef struct { int top[2], bot[2]; SElemType* V; int m; } DblStack; void init(DblStack& dblStack, int size) { dblStack.m = size; dblStack.V = new SElemType[size]; dblStack.bot[0] = 0; dblStack.bot[1] = size - 1; dblStack.top[0] = -1; dblStack.top[1] = size; } void release(DblStack& dblStack) { delete[] dblStack.V; } void display(const DblStack& dblStack) { for (int i = dblStack.bot[0]; i <= dblStack.top[0]; i++) { cout << (dblStack.V[i].data) << " "; } cout << " <> "; for (int i = dblStack.bot[1]; i >= dblStack.top[1]; i--) { cout << (dblStack.V[i].data) << " "; } cout << endl; } bool isEmpty(DblStack& dblStack, int id) { if (id == 0) { return dblStack.top[0] == -1; } else if (id == 1) { return dblStack.top[1] == dblStack.m; } else { return true; } } bool isFull(DblStack& dblStack){ return (dblStack.top[1] - dblStack.top[0] == 1); } void push(DblStack& dblStack, int id, SElemType elem) { if (!isFull(dblStack)) { if (id == 0) { dblStack.V[++dblStack.top[0]] = elem; } else if (id == 1) { dblStack.V[--dblStack.top[1]] = elem; } } } void pop(DblStack& dblStack, int id) { if (!isEmpty(dblStack, id)) { if (id == 0) { dblStack.top[0] --; } else if (id == 1) { dblStack.top[1] ++; } } } int main() { DblStack stack; init(stack, 10); push(stack, 0, SElemType(1)); push(stack, 0, SElemType(2)); push(stack, 0, SElemType(3)); push(stack, 0, SElemType(4)); push(stack, 1, SElemType(5)); push(stack, 1, SElemType(6)); push(stack, 1, SElemType(7)); push(stack, 1, SElemType(8)); push(stack, 1, SElemType(9)); push(stack, 1, SElemType(10)); push(stack, 1, SElemType(11)); push(stack, 0, SElemType(12)); display(stack); pop(stack, 0); pop(stack, 1); pop(stack, 1); display(stack); pop(stack, 0); pop(stack, 0); pop(stack, 0); pop(stack, 0); pop(stack, 1); pop(stack, 1); pop(stack, 1); pop(stack, 1); pop(stack, 1); display(stack); release(stack); return 0; }