大话数据结构08:共享栈 C++
生活随笔
收集整理的這篇文章主要介紹了
大话数据结构08:共享栈 C++
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基礎介紹
共享棧就是一塊內存分配給兩個棧,兩個棧從各自端點向中間生長,就是計算機基礎中內存棧的實現吧
代碼
#include "stdio.h" #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 /* 存儲空間初始分配量 */typedef int Status;typedef int SElemType; /* SElemType類型根據實際情況而定,這里假設為int *///兩棧共享空間結構 typedef struct {SElemType data[MAXSIZE];int top1; /* 棧1棧頂指針 */int top2; /* 棧2棧頂指針 */ }SqDoubleStack;Status visit(SElemType c) {printf("%d ", c);return OK; }Status InitStack(SqDoubleStack* S) {S->top1 = -1;S->top2 = MAXSIZE;return OK; }// 把S置為空棧 const Status ClearStack(SqDoubleStack* S) {S->top1 = -1;S->top2 = MAXSIZE;return OK; }//判斷是否為空棧 Status StackEmpty(SqDoubleStack* S) {if (S->top1 == -1 && S->top2 == MAXSIZE)return TRUE;else{return FALSE;} }//返回元素的個數 int StackLength(SqDoubleStack* S) {return (S->top1 + 1) + (MAXSIZE - S->top2); }//插入元素e為某個棧的新元素 Status Push(SqDoubleStack* S, SElemType e, int stackNumber) {if (S->top1 + 1 == S->top2)return ERROR;else if (stackNumber == 1){S->top1++;S->data[S->top1] = e;}else{S->top2--;S->data[S->top2] = e;}return OK; }//返回棧頂元素 Status Pop(SqDoubleStack* S, SElemType* e, int stackNumber) {if (stackNumber == 1){if (S->top1 == -1)return ERROR;*e = S->data[S->top1--];}else if (stackNumber == 2){if (S->top2 == MAXSIZE)return ERROR;*e = S->data[S->top2++];}return OK; }const Status StackTraverse(SqDoubleStack* S) {int i;i = 0;while (i <= S->top1){visit(S->data[i++]);}i = S->top2;while (i < MAXSIZE){visit(S->data[i++]);}printf("\n");return OK;} int main() {int j;SqDoubleStack s;int e;if (InitStack(&s) == OK){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));return 0; }總結
以上是生活随笔為你收集整理的大话数据结构08:共享栈 C++的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大话数据结构07 :链表栈
- 下一篇: C++ 大话数据结构 09: 中缀表达式