C語言數據結構 判斷出棧序列合法性


體思路看視頻講解 把出棧序列看成是一個隊列,

同時定義一個棧,每次壓入一個元素到棧中,對比棧頂元素和隊頭元素是否相等,若相等則出棧當前元素並且出隊出棧序列

若當前棧頂元素不等於隊列頭元素,則持續壓棧

具體講解看視頻講解:合法性的判斷

#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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM