数据结构之共享栈(堆存储)

来源:互联网 发布:php 二进制打印出来 编辑:程序博客网 时间:2024/05/20 04:13
#include<iostream>using namespace std; const int MAXSIZE = 20;typedef int SElemType;typedef struct HeDoubleStack{SElemType *pBase;int top1;int top2;}HeDoubleStack;void Visit(SElemType c){cout << c;}void InitStack(HeDoubleStack &S){S.pBase = new SElemType[MAXSIZE];S.top1 = -1;S.top2 = MAXSIZE;}void ClearStack(HeDoubleStack &S){S.top1 = -1;S.top2 = MAXSIZE;}void DestroyStack(HeDoubleStack &S){delete[]S.pBase;S.pBase = NULL;S.top1 = -1;S.top2 = MAXSIZE;}bool StackEmpty(HeDoubleStack S){if (S.top1 == -1 && S.top2 == MAXSIZE)return true;elsereturn false;}bool StackFull(HeDoubleStack S){if (S.top1+1==S.top2)return true;elsereturn false;}int StackLength(HeDoubleStack S){return (S.top1 + 1) + (MAXSIZE - 1 - S.top2);}bool Push(HeDoubleStack &S, SElemType e, int stackNumber){if (StackFull(S)) return false;if (stackNumber == 1){S.pBase[++S.top1] = e; /* 若是栈 1 则先 top1+1 后给数组元素赋值。 */return true;}else if (stackNumber == 2)  /* 栈 2 有元素进栈 */{S.pBase[--S.top2] = e; /* 若是栈 2 则先 top2-1 后给数组元素赋值。 */return true;}elsereturn false;}bool Pop(HeDoubleStack &S, SElemType &e, int stackNumber){if (StackEmpty(S))return false;if (stackNumber == 1){e = S.pBase[S.top1--];return true;}else if (stackNumber == 2){e = S.pBase[S.top2++];return true;}elsereturn false;}void StackTraverse(HeDoubleStack S){int i = 0;while (i < S.top1){Visit(S.pBase[i++]);}i = S.top2;while (i < MAXSIZE){Visit(S.pBase[i++]);}cout << endl;}void main(){int j;SElemType e;HeDoubleStack S;InitStack(S);for (j = 1; j <= 5; j++)Push(S, j, 1);for (j = MAXSIZE; j >= MAXSIZE - 2; j--)Push(S, j, 2);printf("栈中元素依次为:");StackTraverse(S);printf("当前栈中元素有:%d \n", StackLength(S));Pop(S, e, 2);printf("弹出的栈顶元素 e=%d\n", e);printf("栈空否:%d(1:空 0:否)\n", StackEmpty(S));for (j = 6; j <= MAXSIZE - 2; j++)Push(S, j, 1);printf("栈中元素依次为:");StackTraverse(S);printf("栈满否:%d(1:否 0:满)\n", Push(S, 100, 1));ClearStack(S);printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(S));}

0 0
原创粉丝点击