具體思路看視頻講解 把出棧序列看成是一個隊列,
同時定義一個棧,每次壓入一個元素到棧中,對比棧頂元素和隊頭元素是否相等,若相等則出棧當前元素並且出隊出棧序列
若當前棧頂元素不等於隊列頭元素,則持續壓棧
具體講解看視頻講解:合法性的判斷
#include<stdio.h> #include<stdbool.h> bool check(int Popped[],int Pushed[]) { int stack[5]={0},top=-1;//設置一個棧 int pop=0;//設置top1在popped中游走,popped表示彈棧的序列 for(int i=0;i<5;i++)//i在入棧序列之中游走 { stack[++top]=Pushed[i];//壓棧一個元素 while(top!=-1&&Popped[pop]==stack[top]){ --top;//若棧不為空且當前棧頂等於出棧序列頭的值,棧頂元素出棧 ++pop;//出棧序列頭元素出隊 } } if(top==-1) return true; else return false; } int main(){ int pushed[5]={1,2,3,4,5}; int popped[5]={3,2,5,4,1}; bool is_true=check(popped, pushed); printf("%d\n",is_true); }