#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 的參考代碼