数据结构学习笔记——第四章:栈

2019-07-20  本文已影响0人  吃远

一、栈

1. 栈的特点

  ①只有最右侧(顶部)元素可见,最左侧(底部)元素不可见
  ②只提供pop和push两个接口用于操作顶部元素
  从形式上看,栈就像堆积凳子或者盘子,last in first out。

2. 栈的实现

  栈的实现可以借助之前已经实现过的Vector类。具体而言就是以Vector类为父类派生出一个子类Stack,然后只需要在Stack类中调用父类的接口,实现栈的pop、push和top即可。

二、栈的应用

  栈适用于以下特点的算法:

template <typename T>
T pop(stack<T> &stk){
    T tp = stk.top();
    stk.pop();
    return tp;
}

template <typename T>
bool is_shuffled(stack<T> targ, stack<T> org){
    stack<T> temp;
    while(!targ.empty()){
        if(!org.empty()) temp.push(pop(org));
        else break;
        cout<<"targ: "<<targ.top()<<" temp: "<<temp.top()<<endl;
        if(targ.top() == temp.top()){
            targ.pop();
            temp.pop();
        } else{
            while(!org.empty() && targ.top() != org.top())
                temp.push(pop(org));
        }
    }
    if(temp.empty()) return true;
    return temp.top() == targ.top() ?
            true: false;
}

int main(){
    int A[]={1,2,3,4,5};
    //int B[]={1,3,2,4,5}; //not permutaed
    //int B[]={2,1,3,4,5}; //permutaed
    int B[]={2,1,3,5,4}; // not permutated
    auto size_A = getArrayLen(A);
    auto size_B = getArrayLen(B);
    stack<int> org;
    stack<int> targ;
    for(int i=0;i<size_A;++i) org.push(A[i]);
    for(int i=0;i<size_B;++i) targ.push(B[i]);
    bool rst = is_shuffled(targ, org);
    cout<<((rst) ? "A is permutated from B!":"A is not permutated from B.")<<endl;
}
➜ compile_gcc stack_permutation.cpp && ./stack_permutation
targ: 4 temp: 5
targ: 4 temp: 4
targ: 5 temp: 3
A is not permutated from B.
上一篇 下一篇

猜你喜欢

热点阅读