Web Navigation
总提交:14 测试通过:13
描述
Standard web browsers contain features to move backward and forward among the pages recently visited. One way to implement these features is to use two stacks to keep track of the pages that can be reached by moving backward and forward. In this problem, you are asked to implement this.
The following commands need to be supported:
BACK: Push the current page on the top of the forward stack. Pop the page from the top of the backward stack, making it the new current page. If the backward stack is empty, the command is ignored.
FORWARD: Push the current page on the top of the backward stack. Pop the page from the top of the forward stack, making it the new current page. If the forward stack is empty, the command is ignored.
VISIT : Push the current page on the top of the backward stack, and make the URL specified the new current page. The forward stack is emptied.
QUIT: Quit the browser.
Assume that the browser initially loads the web page at the URL http://www.acm.org/
输入
输出
样例输入
VISIT http://acm.baylor.edu/acmicpc/
BACK
BACK
BACK
FORWARD
VISIT http://www.ibm.com/
BACK
BACK
FORWARD
FORWARD
FORWARD
QUIT
样例输出
http://acm.baylor.edu/acmicpc/
http://acm.ashland.edu/
http://www.acm.org/
Ignored
http://acm.ashland.edu/
http://www.ibm.com/
http://acm.ashland.edu/
http://www.acm.org/
http://acm.ashland.edu/
http://www.ibm.com/
Ignored
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<stack>
using std::stack;
const string ERROR_MESSAGE = "Ignored";
stack<string> url_front; //存储该页面之前的页面(浏览器前进方向)
stack<string> url_back; //存储该页面之后的页面(浏览器后退方向)以及当前浏览器所在的页面,当前页面在栈顶
void visit(void){
string url;
cin >> url;
url_back.push(url); //保存当前浏览的页面
while (!url_front.empty()){
url_front.pop(); //清空该页面之前的页面
}
cout << url_back.top() << endl;
}
void back(void){
if (url_back.size() > 1){ //后面有页面时才可以后退
url_front.push(url_back.top());
url_back.pop();
cout << url_back.top() << endl;
}
else{
cout << ERROR_MESSAGE << endl;
}
}
void forward(void){
if (!url_front.empty()){ //前面有页面时才可以前进
url_back.push(url_front.top());
url_front.pop();
cout << url_back.top() << endl;
}
else{
cout << ERROR_MESSAGE << endl;
}
}
int main(void){
string command;
url_back.push("http://www.acm.org/");
while (cin >> command, command != "QUIT"){
if (command == "VISIT"){
visit();
}
else if (command == "BACK"){
back();
}
else if (command == "FORWARD"){
forward();
}
}
return 0;
}