29. 栈的push,pop序列
生活随笔
收集整理的這篇文章主要介紹了
29. 栈的push,pop序列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:給定2個整數(shù)序列,其中1個是棧的push順序,判斷另一個有沒有可能是對應(yīng)的pop順序
解:其實(shí)這題主要是判斷進(jìn)棧次數(shù)和出棧次數(shù)誓不是相等。我是用棧作的,效率不高,每一個元素最多出棧1次,進(jìn)棧1此,所以最多進(jìn)行2n次操作,然后每次對棧頂元素和pb指針指向的元素進(jìn)行比較(因?yàn)榧僭O(shè)序列中整數(shù)都不相等)
代碼:
/*判斷棧push和pop順序是否符合push中的元素順序入棧,如果等于pb指向的元素,那么循環(huán)出棧,知道棧空或者pb元素和棧頂元素不一樣,如果一樣,出棧且pb++,總共的入棧出棧次數(shù)最多是2*n次*/#include<iostream> using namespace std; #define MAX 50typedef struct {int data[MAX];int top; }Stack;Stack* create_stack(void) {Stack* s=new Stack;if(s)s->top=-1;return s; }bool empty_stack(Stack* s) {if(-1==s->top)return true;return false; }bool full_stack(Stack* s) {if(MAX-1==s->top)return true;return false; }void push_stack(Stack* s,int value) {if(full_stack(s))return ;s->top++;s->data[s->top]=value; }int pop_stack(Stack* s) {if(empty_stack(s))return -1;int temp=s->data[s->top];s->top--;return temp; }int get_stack(Stack* s) {if(empty_stack(s))return -1;return s->data[s->top]; }void free_stack(Stack* s) {if(s){delete s;s=NULL;} }bool satisfy(int *a,int *b,int n) {int i=0;int pa,pb;Stack* s;pa=0;pb=0;s=create_stack();while(i++<2*n){if(pa==n && pb==n)break;if(pa<n){ push_stack(s,a[pa]);pa++;}while(!empty_stack(s) && get_stack(s)==b[pb]){pop_stack(s);pb++;}}bool flag;if(empty_stack(s) && pb==n)flag=true;elseflag=false;free_stack(s);return flag;}int main(void) {int a[MAX];int b[MAX];int n,i;cin>>n;for(i=0;i<n;i++)cin>>a[i];for(i=0;i<n;i++)cin>>b[i];cout<<boolalpha;cout<<satisfy(a,b,n)<<endl;return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/buxianghe/p/3262418.html
總結(jié)
以上是生活随笔為你收集整理的29. 栈的push,pop序列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 代码生成器1.0正式发布
- 下一篇: 常见的排序方法