当前位置:编程学习 > C/C++ >>

栈的push、pop序列

题目:输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。因为可以有如下的push和pop序列:push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,这样得到的pop序列就是4、5、3、2、1。但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

 

 

[cpp]
#include <iostream>  
using namespace std; 
const int MAXSIZE=10; 
template<class T> 
class stack 

public: 
    stack(); 
    ~stack(); 
    bool push(T value); 
    bool pop(); 
    bool empty(); 
    T top(); 
private: 
    T s[MAXSIZE];//栈对应的元素  
    int head;//指向栈顶元素  
}; 
 
template<class T> 
bool stack<T>::empty() 

    return head==-1?1:0; 

 
template<class T> 
stack<T>::stack() 

    head=-1; 

 
template<class T> 
stack<T>::~stack() 


 
template<class T> 
bool stack<T>::push(T value) 

    if((MAXSIZE-1)==head){ 
        cout<<"栈已满"<<endl; 
        return false; 
    } 
    s[++head]=value; 
    return true; 

 
template<class T> 
bool stack<T>::pop() 

    if(-1==head){ 
        cout<<"栈已空"<<endl; 
        return false; 
    } 
    --head; 
    return true; 

 
template<class T> 
T stack<T>::top() 

   if(-1==head) 
       throw 1; 
   else 
       return s[head]; 

 
bool Is_Pop(int *a,int *b,int len_a,int len_b) 

    if(len_a!=len_b) 
        return false; 
    stack<int> s; 
    int i=1,j=1; 
    while(j!=len_a){ 
        //如果输入的b数组数字有问题  
        if(b[j]<1 || b[j]>=len_a) 
            return false; 
        //如果数组a全部入栈,那么依次出栈和b[j]比较  
        if(i==len_a){ 
            while(!s.empty()){ 
                if(s.top()!=b[j++]) 
                    return false; 
                s.pop(); 
            } 
            return true; 
        } 
        if(a[i]<b[j]){ 
            s.push(a[i++]); 
        } 
        else { 
            s.push(a[i]); 
            ++i; 
            ++j; 
            s.pop(); 
        } 
    }     
    return true; 

 
void main() 

    stack<int> s; 
    int Push[]={0,1,2,3,4,5};//从Push[1]开始  
    int Pop[]={0,4,3,5,1,2};//从Pop[1]开始  
    cout<<Is_Pop(Push,Pop,sizeof(Push)/sizeof(int),sizeof(Pop)/sizeof(int)); 
    system("pause"); 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,