栈
栈只允许在栈顶操作,不允许在中间位置进行插入和删除操作,不支持数组表示法和随机访问。使用stack
时需要引入头文件#include<stack>
。
stack<int>s
:创建一个空栈s
,数据类型为int
。push(x)
:x
入栈。pop()
:出栈。top()
:取栈顶(未出栈)。empty()
:判断栈是否为空,若为空则返回true
。size()
:求栈大小,返回栈中的元素个数。
题目描述
标准的Web浏览器包含在最近访问过的页面中向后和向前移动的功能。实现这些特性的一种方法是使用两个栈来跟踪前后移动可以到达的页面。支持一下命令:
- BACK:将当前页面推到前向栈的顶部。从后向栈的顶部弹出页面,使其称为新的当前页面。如果后向栈为空,则忽略该命令。
- FORWARD:将当前页面推到后向栈的顶部。从前向栈顶部弹出页面,使其称为新的当前页面。如果前向栈为空,则忽略该命令。
- VISIT:将当前页面推到后向栈的顶部,使URL成为新的当前页面。前向栈清空。
- QUIT:退出浏览器。
#include<iostream>
#include<stack>
int main()
{
using namespace std;
stack<string> backward;
stack<string> forward;
string c;
string cur = "http://www.acm.org";
while(cin >> c && c!= "QUIT"){
if(c == "VISIT"){
backward.push(cur);//入后向栈
cin >> cur;
cout << cur <<endl;
while(!forward.empty()){//若前向栈不为空,则清空
forward.pop();//出栈
}
}
else if(c == "BACK"){
if(backward.empty()){//判断栈是否为空,若为空则返回true
cout << "Ignored" << endl;
}
else{
forward.push(cur);//入前向栈
cur = backward.top();//取后向栈栈顶元素
backward.pop();
cout<< cur <<endl;
}
}
else{
if(forward.empty()){
cout << "Ignored" << endl;
}
else{
backward.push(cur);//如后向栈
cur = forward.top();//取前向栈栈顶元素
forward.pop();
cout << cur << endl;
}
}
}
return 0;
}
输入:
VISIT http://acm.ashland.edu/
VISIT http://acm.baylor.edu/acmicpc/
BACK
BACK
BACK
FORWARD
VISIT http://www.ibm.com/
BACK
BACK
FORWARD
FORWARD
FPRWARD
QUIT
输出:
http://acm.ashland.edu/
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