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
",is_true);
}
原文地址:https://www.cnblogs.com/oldfish123/p/13691790.html