队列和栈
#include<queue>//头文件
queue<int> q;//定义队列
q.front();//返回队头元素,但不删除
q.pop();//删除队头元素 但不返回值
q.empty();//判断队列是否为空,为空返回true
q.size();//返回队列中元素个数
q.push(x);//向队列加入新元素(入队),x为值
q.back();//返回队尾元素的值,但不删除
#include<stack>//头文件
stack<int> s;//定义栈
s.top();//返回栈顶元素,但不删除
s.pop();//删除栈顶元素,但不返回
s.size();//返回栈内元素个数
s.push(x);//向栈内入栈新元素(入栈),值为x
s.empty();//判断栈是否为空,为空返回true
运用实例
纸牌游戏:小猫钓鱼
俩玩家分别持有一定数量纸牌
玩家1先出牌放到桌面,玩家2再出牌
如果玩家出的牌在桌面上已有,则该玩家可以获得俩张牌中间所有的牌
俩玩家的牌库可以看做是队列,先进先出
桌面可看做栈,先进后出
queue<char> a;//玩家1
queue<char> b;//玩家2
stack<char> m;//桌面
bool book[15];//标记数组
//将字符串中每个元素转换为相应int值,便于book数组标记
int z(char x){
if(x=='A') return 1;
else if(x=='2') return 2;
else if(x=='3') return 3;
else if(x=='4') return 4;
else if(x=='5') return 5;
else if(x=='6') return 6;
else if(x=='7') return 7;
else if(x=='8') return 8;
else if(x=='9') return 9;
else if(x=='+') return 10;
else if(x=='J') return 11;
else if(x=='Q') return 12;
else if(x=='K') return 13;
}
//玩家1赢牌
void d1(int t,char s){
while(book[t])
{
int n=z(m.top());
a.push(m.top());
book[n]=false;
m.pop();
}
return;
}
//玩家2赢牌
void d2(int t,char s){
while(book[t])
{
int n=z(m.top());
b.push(m.top());
book[n]=false;
m.pop();
}
return;
}
int main(){
string str1,str2;
cin>>str1>>str2;
for(int i=0;i<15;i++) //初始化book数组
{
book[i]=false;
}
for(int i=0;i<str1.length();i++)
{
a.push(str1[i]);
}
for(int i=0;i<str2.length();i++)
{
b.push(str2[i]);
}
while(!a.empty()&&!b.empty()) //当俩玩家牌库均不为空,玩家1先出牌
{
int t;
t=z(a.front());
if(book[t])//赢牌将队首重新入队到队列,将赢得的牌在入队列
{
char c=a.front();
a.push(c);
a.pop();
d1(t,c);
}
else
{
book[t]=true;
m.push(a.front());
a.pop();
if(a.empty()) break;
}
t=z(b.front());
if(book[t])
{
char c=b.front();
b.push(c);
b.pop();
d2(t,c);
}
else{
book[t]=true;
m.push(b.front());
b.pop();
}
}
if(a.empty())
{
cout<<"后者获胜!"<<endl;
/*while(!b.empty())
{
cout<<b.front()<<" ";
b.pop();
}
cout<<endl;
while(!m.empty())
{
cout<<m.top()<<" ";
m.pop();
}
cout<<endl;*/
}
else if(b.empty()) cout<<"前者获胜!"<<endl;
return 0;
}