WA了好多次,注意的是进出栈的先后顺序,还有相关的判断。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
typedef struct wuliao
{
char s[60];
}ss;
stack<ss> Back,For;
char flag[10];
ss url,tmp;
void unit()
{
while(!Back.empty())
Back.pop();
while(!For.empty())
For.pop();
}
int main()
{
int T,t;
cin>>T;
for(t=1;t<=T;t++)
{
unit();
strcpy(tmp.s,"http://www.lightoj.com/");
cout<<"Case "<<t<<":"<<endl;
while(~scanf("%s",flag)&&strcmp(flag,"QUIT")!=0)
{
if(strcmp(flag,"VISIT")==0)
{
Back.push(tmp);
cin>>tmp.s;
cout<<tmp.s<<endl;
while(For.size())
For.pop();
}
else if(strcmp(flag,"BACK")==0)
{
if(Back.empty())
cout<<"Ignored"<<endl;
else
{
For.push(tmp);
tmp=Back.top();
Back.pop();
cout<<tmp.s<<endl;
}
}
else if(strcmp(flag,"FORWARD")==0)
{
if(For.empty())
cout<<"Ignored"<<endl;
else
{
Back.push(tmp);
tmp=For.top();
For.pop();
cout<<tmp.s<<endl;
}
}
else continue;
}
}
return 0;
}
推荐一个写的比较漂亮的代码:
#include <cstdio>
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
stack<string>F,B;
string str="http://www.lightoj.com/",command;
printf("Case %d:\n",i);
while(cin>>command&&command!="QUIT")
{
if(command=="BACK")
{
if(B.empty())
printf("Ignored\n");
else
{
F.push(str);
str=B.top();
B.pop();
cout<<str<<endl;
}
}
else if(command=="FORWARD")
{
if(F.empty())
printf("Ignored\n");
else
{
B.push(str);
str=F.top();
F.pop();
cout<<str<<endl;
}
}
else
{
B.push(str);
cin>>str;
cout<<str<<endl;
while(F.size())
F.pop();
}
}
}
return 0;
}