日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

练习3.21

發(fā)布時間:2025/3/14 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 练习3.21 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述:

編寫一個用數組實現的兩個棧的例程。除非數組的每一個單元都被使用,棧例程不能有溢出聲明。

思路:

用一個結構體表示兩個棧,有兩個頭指針,一個從頭開始,另一個從末尾開始。

如果兩個堆棧的頭指針相鄰了,就說明所有空間都被占用了,即堆棧滿了。

#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

?

轉載于:https://www.cnblogs.com/2018zxy/p/10034512.html

總結

以上是生活随笔為你收集整理的练习3.21的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。