栈的push、pop序列(29)
2013-05-19 15:51
309 查看
29.栈的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序列。
函数cfun中的bool变量bl代表要不要将数据压入栈中,最开始需要压入数据,以后则是为空或者栈顶元素不等于b[j]压入元素。最后如果栈为空,那么说明是一个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序列。
#include<iostream> #include<iomanip> using namespace std; /* 下面的代码演示了如何写一个堆栈类,数组的个数传进来,类型用模板 */ template<typename T> class stack { public: stack(int len):m_top(-1),m_len(len) { this->m_stack=new T[len]; } ~stack() { delete []m_stack; // 错误的写法 delete m_stack; } bool empty() { if(-1==m_top) return true; else return false; } T top() { return m_stack[m_top]; } const T pop() { return m_stack[m_top--]; } void push(T v) { if(m_top>=m_len-1) return ; else m_stack[++m_top]=v; } private: int m_top; T *m_stack; const int m_len; //大小,定义成 const类型 }; bool cfun(int *a,int *b,const int len) //len 代表序列长度 { int i,j; bool bl; stack<int> mystack(len); for(i=0,j=0,bl=false;i<len&&j<len;) //错误的写法:for(i=0,j=0,bl=false;i<len,j<=len;) { if(!bl) // 为空或者不等于b[j]就压入新元素 { mystack.push(a[i]); } if(!mystack.empty()&&mystack.top()==b[j]) { mystack.pop(); j++; bl=true; } else { bl=false; i++; } } if(mystack.empty()) return true; else return false; } int main() { int a[]={1,2,3,4,5}; int b[]={4,3,5,1,2}; bool bl=cfun(a,b,5); if(bl) cout<<"yes"; else cout<<"no"; cout<<endl; system("pause"); return 0; }
函数cfun中的bool变量bl代表要不要将数据压入栈中,最开始需要压入数据,以后则是为空或者栈顶元素不等于b[j]压入元素。最后如果栈为空,那么说明是一个pop序列
相关文章推荐
- 29.栈的push、pop序列
- 29 栈的 push、pop 序列
- 29.栈的push、pop 序列
- 29、栈的push、pop序列
- Q29、栈的 push、pop 序列(栈)
- 算法习题29:栈的push、pop序列是否一致
- 微软面试100题之29题:栈的push、pop 序列
- 29.栈的push、pop 序列
- 29.栈的push、pop序列(栈)
- 29. 栈的push,pop序列
- 29.栈的push、pop 序列
- 栈的push、pop 序列测试
- 程序员面试题精选100题(24)-栈的push、pop序列[数据结构]
- 25. 微软面试题:栈的push、pop序列(栈)
- 第29题:推断一个序列是否是还有一个push序列的pop序列
- 栈的push、pop序列
- 每天学习一算法系列(27)(输入两个整数序列。其中一个序列表示栈的push 顺序,判断另一个序列有没有可能是对应的pop 顺序)
- 栈的push、pop序列
- PHP 输入两个整数序列。其中一个序列表示栈的push 顺序, 判断另一个序列有没有可能是对应的pop 顺序
- 栈的push、pop 序列