【題目描述】用棧完成模擬網(wǎng)頁:
輸入 open,輸入要打開的地方。
輸入now,輸出當(dāng)前網(wǎng)頁。
輸入back,輸出上一個網(wǎng)頁,若沒有,輸出no。
輸入over,關(guān)閉網(wǎng)頁。
【樣例輸入】open http://www.itdecent.cn/u/c2cdbbbb7678
open http://www.itdecent.cn/
now
back
back
over
【樣例輸出】http://www.itdecent.cn/
http://www.itdecent.cn/u/c2cdbbbb7678
no
棧.push(n) 進(jìn)入棧
棧.pop() 刪除棧頂元素
棧.empty() 1為空,0為滿。
棧.top() 棧頂元素
stack<類型> 棧; 命名一個棧
這道題可以依次用if語句判斷,別忘了加上頭文件#include <stack>
今天直接上完整代碼~
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<string> s;//此處要用字符串類型
while(1){
string st;
cin>>st;
if(st=="open"){
string d;
cin>>d;
s.push(d);//入棧
}
if(st=="now") cout<<s.top()<<endl;//輸出棧頂元素
if(st=="back"){
s.pop();//先彈出棧頂元素
if(s.empty()==0) cout<<s.top()<<endl;//判斷棧是否為空
if(s.empty()==1) cout<<"no"<<endl;
}
if(st=="over"){
break;//結(jié)束循環(huán)
}
}
return 0;
}