/*
标准的Web浏览器包含前后翻页的功能,现在要你自己设计数据结构和算法,实现以下指令:
BACK:将当前页面压入前进堆栈,将后退堆栈弹出,并设置为当前网页,若后退堆栈为空,则忽略
FORWARD:将当前页面压入后退堆栈,将前进堆栈顶页面弹出,并设置为当前网页,若前进堆栈为空,则忽略
VISIT:将当前网页压入后退堆栈,将url设置为新的当前网页,清空前进网页。
QUIT:推出浏览器;
分析:数据结构选择stack,分为前进和后退,算法就是简单模拟
*/
#include
<iostream>
#include
<cstdio>
#include
<vector>
#include
<stack>
#include
<cstring>
#include
<string>
#include
<sstream>
using
namespace
std;
string current_url
=
"";
stack
<string
> Back,Forward;
bool
back(){
//将当前页面压入前进栈,将后退栈顶的网页弹出,并设置为新的当前网页,若后退栈为空,则忽略本命令
if(
!Back.
empty()){
Forward.
push(current_url);
current_url
=Back.
top();
Back.
pop();
return
true;
}
return
false;
}
bool
forward(){
//将当前网页压入backstack,将forwardstack顶网页弹出,并设置为新的当前网页,若forwardstack
if(
!Forward.
empty()){
Back.
push(current_url);
current_url
=Forward.
top();
Forward.
pop();
return
true;
}
return
false;
}
void
visit(string url){
//将当前网页压入backstack,将url设置为新的当前网页,并且清空前进网页
Back.
push(current_url);
//为什么要在visit后清空forwardstack,因为visit代表访问了新的网页,自然不可能有踪迹
current_url
=url;
while(
!Forward.
empty())
Forward.
pop();
}
vector
<string
>
webNavigation(vector
<string
>
&cmds){
int n
=cmds.
size();
vector
<string
> result;
for(
int i
=
0;i
<n;i
++){
istringstream
strstr(cmds[i]);
string cmd,aline
=
"Ignored";
strstr
>>cmd;
if(cmd
==
"BACK"
&&
back()) aline
=current_url;
else
if (cmd
==
"FORWARD"
&&
forward()) aline
=current_url;
else
if(cmd
==
"VISIT"){
string url;
strstr
>>url;
visit(url);
aline
=current_url;
}
result.
push_back(aline);
}
return result;
}
int
main(){
string command;
vector
<string
> cmds;
getline(cin,command);
while(command
!=
"QUIT"){
cmds.
push_back(command);
getline(cin,command);
}
vector
<string
> result
=
webNavigation(cmds);
for(vector
<string
>::iterator i
=result.
begin();i
!=result.
end();i
++)
cout
<<*i
<<endl;
getchar();
getchar();
return
0;
}
/*
补充:
istringstream的用法,首先istringstream包含在名为sstream的头文件中:
它是c++的一个输入控制类
istringstream的构造函数如下:
istringstream::istringstream(string str);
它的用法通过以下一个例子理解:
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(){
string str="this is a book";
istringstream strstr(str);
string s;
while(strstr>>s)
cout<<s<<endl;
return 0;
}
输出为:
this
is
a
book
*/