标签:
#include <iostream> #include <stack> using namespace std; int main() { stack<int>s; //声明栈s的元素类似是int s.empty() //栈空,返回true, 否则返回false s.push(1); //1进栈 s.top(); //取栈顶元素 s.pop(); //栈顶元素出栈 return 0; }
图1-1 标准模板库stack的使用示例
#include <iostream> #include <stack> using namespace std; int main() { int stk[1000], top=0; top = 0; //栈空 stk[++top] = 1; //1进栈 stk[-- top]; //取栈顶元素 top--; //出栈 return 0; }
图1-2 用数组实现简单的栈
#include <iostream> #include <stack> #include <string> using namespace std; int main() { string cmd, visit = "http://www.acm.org/"; stack<string>Forward, Back; while(cin>>cmd && cmd != "QUIT") { if(cmd == "VISIT") { Back.push(visit); while(!Forward.empty()) Forward.pop(); cin>>visit; } else if(cmd == "FORWARD") { if(Forward.empty()) { cout<<"Ignored"<<endl; continue; } else { Back.push(visit); visit = Forward.top(); Forward.pop(); } } else if(cmd == "BACK") { if(Back.empty()) { cout<<"Ignored"<<endl; continue; } else { Forward.push(visit); visit = Back.top(); Back.pop(); } } else printf("Invalid input!\n"); cout<<visit<<endl; } return 0; }
图1-3 TOJ1196 Web Navigation的参考代码
#include <stdio.h> #include <stdlib.h> #include <stack> using namespace std; int main() { stack<int>s; int n, i, j; while(scanf("%d", &n) && n) { //init block int a[n]; while(scanf("%d", &a[0]) && a[0]) { for(i=1; i<n; i++) { scanf("%d", &a[i]); } //judge j = 1, i=0; while(!s.empty()) s.pop(); while(i < n) { //push j when j<=a[i] while(j <= a[i]) { s.push(j); j++; } //pop s.top if s.top() == a[i] while(!s.empty() && s.top() == a[i]) { s.pop(); i++; } //根据LIFO, s.top()永远应该<=a[i] if(!s.empty() && s.top()>a[i]) break; } if(s.empty()) printf("Yes\n"); else printf("No\n"); } printf("\n"); } return 0; }
图1-4 TOJ 1036 Rails 的参考代码
标签:
原文地址:http://www.cnblogs.com/vsky/p/5006981.html