栈1(火车进站)

问题描述

某城市有一个火车站,有n节车厢从A方向驶入车站,按进站的顺序编号为1~n。现让它们按照某种特定的顺序进入B方向的铁轨并驶出车站。为了重组车厢,你可以借助中转站C。在程序中输入车厢数目和出站的特定顺序,如果可以则输出Yes,否者输出No。

样例输入:

5

1 2 3 4 5

5

5 4 1 2 3

6

6 5 4 3 2 1

样例输出:

Yes

No

Yes

#include"iostream"
using namespace std;

template<typename T>
class stack{
private:
    T *arr;
    int atop;
    int size;
public:
    stack(int size);
    bool push(T data);
    bool empty();
    T pop();
    T top();
};

bool judge(int *train);
int main(){
    int train[100] = {4,5,3,2,1};
    cout.setf(ios::boolalpha);
    cout<<judge(train)<<endl;
    return 0;
}

bool judge(int *train){
    stack<int> s(100);
    int i = 0;
    int j = 0;
    while(train[j]!=''){
        if(s.empty()||s.top() < train[j]){
            s.push(++i);
        }
        else if(s.top()==train[j]){
            s.pop();
            j++;
        }
        else{
            return false;
        }
    }
    if(s.empty()){
        return true;
    }
    else{
        return false;
    }
}


template<typename T>
stack<T>::stack(int size){
    arr = new T[size];
    atop = 0;
    this->size = size;
}
template<typename T>
bool stack<T>::push(T data){
    if(atop >= size){
        cout<<"out of space!";
        return false;
    }
    arr[atop++] = data;
    return true;
}
template<typename T>
bool stack<T>::empty(){
    return atop == 0;
}
template<typename T>
T stack<T>::pop(){
    if(!empty()){
        return arr[--atop];
    }
    else{
        cout<<"is empty"<<endl;
        return arr[size];
    }
}
template<typename T>
T stack<T>::top(){
    return arr[atop - 1];
}
原文地址:https://www.cnblogs.com/oleolema/p/9033077.html