队列是FIFO,因为先进先出,和排队一样。
卡牌游戏
扔出第一张并把新的第一张放入最后
//int q[100]={1,2,3,4,5,6,7};
int q[100];
void c()
{
int front,rear;
//front是第一个元素,rear是最后一个元素的后一个位置
front=0;
rear=7;
while(front<rear) //当且仅当
{
printf("%d",q[front]);//输出第一个元素
front++;//向后推移一位= 抛弃了第一张牌
q[rear]=q[front];//将当前的第一张牌扔到最后面去
rear++;//此时最后一张牌已经发生了改变
front++;//继续抛弃,这回的抛弃是因为此牌已经移开
//直到 front = rear 因为f每次增2 r每次增1,所以应该会执行n次
}
}
void cpp()
{
queue<int> q;//声明一个队列
for(int i=1;i<=7;i++)
q.push(i);
while(!q.empty())
{
cout<<q.front();
q.pop();
q.push(q.front());
q.pop();
}
}
堆栈是LIFO 最后一个进入的第一个出去,
车站游戏
int n=5,target[1000]={0,3,2,1,5,4};
void c()
{
int stack[1000],top=0;
//stack是栈,用于临时存车
//top是指向栈顶的符号,如果top=0则说明栈内无元素
int A=1,B=1;// A表示正在从A进入栈的车号 也是入栈的次数
//B 表示即将要进入B站的车的序列号 target[B] 是车号
int ok=1;//标识
while(B<=n) //当B=n时说明已经完全出站
{
//目标是出站,所以有限考虑能否出战
if(A==target[B])//此处往往是出站的转折点 此时进入的车正好是要出去的车
{ A++;B++;} //继续进车 继续出车
else if(top&&stack[top]==target[B])//继续出站
{ top--;B++;}
else if(A<=n)//如果暂时不能出站就进站
{ stack[++top]=A++;}
else
{ok=0;break;}
}
printf("%s\n",ok?"Yes":"No");
}
int main()
{
stack<int> s;
int A=1,B=1;
int ok=1;
while(B<=n)
{
if(A==target[B])
{A++;B++;}
else if(!s.empty()&&s.top()==target[B])//empty判断是否空 top 取最顶的元素
{s.pop();B++;}//pop 出栈
else if(A<=n)
{s.push(A++);}//push入栈
else
{ok=0;break;}
}
printf("%s\n",ok?"Yes":"No");
}