练习3.21
問題描述:
編寫一個(gè)用數(shù)組實(shí)現(xiàn)的兩個(gè)棧的例程。除非數(shù)組的每一個(gè)單元都被使用,棧例程不能有溢出聲明。
思路:
用一個(gè)結(jié)構(gòu)體表示兩個(gè)棧,有兩個(gè)頭指針,一個(gè)從頭開始,另一個(gè)從末尾開始。
如果兩個(gè)堆棧的頭指針相鄰了,就說明所有空間都被占用了,即堆棧滿了。
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; const int maxn = 120; struct Node{int top1;int top2;int size;int *array; }; typedef struct Node* Stack;int IsEmpty1(Stack S) {return S->top1==-1; }int IsEmpty2(Stack S) {return S->top2==S->size; }int IsFull(Stack S) {if(S->top2-S->top1==1) return true;else return false; }int Top1(Stack S) {return S->array[S->top1]; }int Top2(Stack S) {return S->array[S->top2]; }void Push1(int x,Stack S) {if(!IsFull(S)) S->array[++S->top1]=x; }void Pop1(Stack S) {if(!IsEmpty1(S)) S->top1--; }void Pop2(Stack S) {if(!IsEmpty2(S)) S->top2++; }void Push2(int x,Stack S) {if(!IsFull(S)) S->array[--S->top2]=x; }Stack CreateStack(int maxsize) {Stack S;S=(Stack)malloc(sizeof(struct Node));if(S==NULL) printf("Out of Space!!!\n");if(maxsize>maxn) printf("too small\n");S->size=maxsize;S->array=(int*)malloc(sizeof(int)*S->size);if(S->array==NULL) printf("Out of Space!!!\n");S->top1=-1;S->top2=S->size;return S; }int main(void) {int n,x,i;Stack S=CreateStack(maxn);cin>>n;for(i=0;i<n;i++){cin>>x;Push1(x,S); }cin>>n;for(i=0;i<n;i++){cin>>x;Push2(x,S);}while(!IsEmpty1(S)){cout<<Top1(S)<<" ";Pop1(S);}cout<<endl;while(!IsEmpty2(S)){cout<<Top2(S)<<" ";Pop2(S);}cout<<endl;return 0; } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/2018zxy/p/10034512.html
總結(jié)
- 上一篇: SNMP学习笔记之SNMPv3的配置和认
- 下一篇: vue 双向数据绑定的实现学习(一)