题目:http://poj.org/problem?id=1363
这个题目题意很简单。给你一组数据,让你判断存在不存在这样的出栈顺序,。
这道题是数据结构一个实验,我选了这个,做一下练习吧!
这个代码是具体栈的实现,
#include<iostream>
using namespace std;
#define size 1010
struct sta
{
int *top;
int *base;
int stasize;
};
int sta_init(sta &s)
{
s.base=new int [sizeof(int)*size];
if(!s.base) return 0;
s.top=s.base;
s.stasize=size;
return 1;
}
void sta_push(sta &s,int x)
{
*s.top++=x;
}
void sta_pop(sta &s)
{
--s.top;
}
bool sta_e(sta &s)
{
if(s.top==s.base) return 1;
return 0;
}
int t[1010];
int main()
{
int n;
while(cin>>n,n)
{
sta S;
sta_init(S);
int i,j;
while(cin>>t[0],t[0])
{
while(!sta_e(S))
sta_pop(S);
for(i=1;i<n;i++)
cin>>t[i];
j=0;
for(i=1;i<=n;)
{
while(sta_e(S) || (!sta_e(S)&&(*(S.top-1)<t[j])))
sta_push(S,i++);
while(!sta_e(S)&&(*(S.top-1)==t[j]))
{ j++;sta_pop(S); }
if(j<n && !sta_e(S) && (*S.top>t[j]))
break;
}
if(sta_e(S))
cout<<"Yes\n";
else
cout<<"No\n";
}
cout<<endl;
}
return 0;
}
下面这个是调用的库函数。作为参考
#include<stdio.h>
#include <stack>
using namespace std;
int main()
{
int n;
while(scanf("%d", &n) && n)
{
stack<int> sta;
int s[1001],i;
while(scanf("%d", &s[0]))
{
while(!sta.empty()) sta.pop();
if(s[0]==0) { putchar('\n'); break;}
for(i=1; i<n; i++)
scanf("%d", &s[i]);
int j=0;
for(i=1; i<=n;)
{
while(sta.empty() || (!sta.empty() && sta.top()<s[j]))
sta.push(i++);
while(!sta.empty() && sta.top()==s[j])
j++,sta.pop();
if(!sta.empty() && j<n && sta.top()>s[j])
break;
}
puts(sta.empty()?"Yes":"No");
}
}
}

1932

被折叠的 条评论
为什么被折叠?



