29.栈的push、pop 序列

来源:互联网 发布:sql regexp replace 编辑:程序博客网 时间:2024/05/22 13:34

 题目:输入两个整数序列。其中一个序列表示栈的push 顺序,
判断另一个序列有没有可能是对应的pop 顺序。
如果我们希望pop 的数字正好是栈顶数字,直接pop 出栈即可;
如果希望pop 的数字目前不在栈顶,我们就到
push 序列中还没有被push 到栈里的数字中去搜索这个数字,
并把在它之前的所有数字都push 进栈。
如果所有的数字都被push 进栈仍然没有找到这个数字,表明该序列不可能是一个pop 序列。

我们来着重分析下此题:
push 序列已经固定,
push     pop
--- -- ->   /---->
5 4 3 2 1   / 4 5 3 2 1
| 5 |
| 4 |
| 3 |
| 2 |
|1  |
1.要得到4 5 3 2 1 的pop 序列,即pop 的顺序为4->5->3->2->1
首先,要pop4,可让push5 之前,pop4,然后push5,pop5
然后发现3 在栈顶,直接pop 3..2..1
2.再看一序列,
push pop
--- -- -> /---->
5 4 3 2 1 / 4 3 5 1 2
| 5 |
| 4 |
| 3 |
| 2 |
|___1__|
想得到4 3 5 1 2 的pop 序列,是否可能? 4->3->5->1->2
同样在push5 之前,push 了4 3 2 1,pop4,pop 3,然后再push 5,pop5
2
再看栈中的从底至上是1 ,由于1 2 已经在栈中,所以只能先pop2,才能pop1。
所以,很显然,不可能有4 3 5 1 2 的pop 序列。

所以,当我要pop 一个数时,先看这个数在不在已经push 的栈顶,如果,在,好,直接pop 它。
如果,不在,那么,从push 序列中,去找这个数,找到后,push 它进栈,
如果push 队列中它的前面还有数,那么还得把它前面数,先push 进栈。
如果push队列中没有这个数,那当然就不是存在这个pop 结果了。

 

我自已写的代码 ,主要用了C++中的容器list和stack,避免使用指针而出错,不过,指针还是要好 好学习啊!

#include<iostream>#include<list>#include<stack>using namespace std;

bool Ispoporder(list<int> pushlist,list<int> poplist){ if(pushlist.empty()||poplist.empty())  return false;  stack<int> s; for(list<int>::iterator iter=poplist.begin();iter!=poplist.end();iter++) {  if(!s.empty()&&(*iter)==s.top())   s.pop();  else  {   //list<int>::iterator it=index(pushlist,*iter);   list<int>::iterator it=pushlist.begin();   while(it!=pushlist.end())   {    if((*it)!=(*iter))     it++;    else     break;   }   //此while循 环是list的查找,可以直接用stl里的查找算法;   if(it==pushlist.end())    return false;   else   {    list<int>::iterator it1=pushlist.begin();    while(it1!=it)    {     s.push(*it1);     it1++;     pushlist.pop_front();    }    s.push(*it);    pushlist.pop_front();   }   s.pop();  }

 } return true;

}

int main(){ list<int> pushlist; list<int> poplist; int a[5]={1,2,3,4,5}; int b[5]={4,3,5,1,2}; for(int i=0;i<5;i++)  pushlist.push_back(a[i]); for(int i=0;i<5;i++)  poplist.push_back(b[i]); if(Ispoporder(pushlist,poplist))  cout<<"is"; else  cout<<"is not";}

原创粉丝点击