知道了栈和队列的初步概念后,就需要开始运用它们做题;
在做题之前,了解几个小细节;
【1】当队头等于队尾等于0时,队列为空;当栈顶为0时,栈内为空;
【2】做题时一定要仔细看题目的要求,在对应的地方进行操作,比如说:题目是让你在所有的运算结束后再输出,那你的输出就一定要在最后。
【3】一般来说,题目都会有要求多组输入分别输出对应结果的,这个时候一定要注意:某些变量在新的一次运算开始之前需要重新赋值为0(这里只是我所遇到的一些情况);
【4】数组一定要开大,至少要比题目给出的需求大
题目1:
实现下面三种操作:
1.enqueue x,将元素x插入队尾。
2.dequeue,若队列非空,则删去队头元素,并输出该元素。
3.query,从队头开始删除所有元素,并输出。
(其中小要求不一一列出了)
//多组输入
#include <stdio.h>
#include <string.h>
//队列
int Q[500000];
int front=0,back=0;
//将一个元素插入队列中
void push(int x)
{
Q[back++]=x;
}
void enqueue(int x)
{
push(x);
}
void dequeue()
{
//如果栈为空输出“this is empty!”并换行
if(front==back)
{
printf("this is empty!\n");
}
else
{
printf("%d\n",Q[front]);
front++;
}
}
void query()
{
//如果栈为空输出“this is empty!”并换行
if(front==back)
{
printf("this is empty!\n");
}
else
{
while(front!=back)
{
printf("%d\n",Q[front++]);
}
}
}
int main()
{
int T;
char str[100];
int x;
int i;
while(~scanf("%d",&T))
{
//一定要在后一次使用之前让其变为0,再进入下一次运算
front=0;
back=0;
for(i=0; i<T; i++)
{
scanf("%s",str);
if(strcmp(str,"enqueue")==0)
{
scanf("%d",&x);
enqueue(x);
}
else if(strcmp(str,"dequeue")==0)
{
dequeue();
}
else if(strcmp(str,"query")==0)
{
query();
}
}
//题目要求每组数据后有一个空行
printf("\n");
}
return 0;
}
题目2:
给定一系列push k和pop操作,若队列或栈已经空了,仍然接收到pop操作,则输出error。
(这个题目和上面的题简直不能说不是一模一样)
//一定要记得当序列为空时,无论多少个pop操作都只输出两个error
#include<stdio.h>
#include<string.h>
int queue[500000]= {0};
int front=0,back=0;
int stack[500000]= {0};
int top=0;
void push(int x)
{
queue[back++]=x;
stack[top++]=x;
}
void pop()
{
--top;
front++;
}
int main()
{
int n,num;
int a[500000];
int x;
int m;
scanf("%d",&m);
getchar();
for(int i=0; i<m; i++)
{
front=0;
back=0;
top=0;
int flag=1;
scanf("%d",&n);
char str[100];
for(int j=0; j<n; j++)
{
scanf("%s",str);
if(strcmp(str,"push")==0)
{
scanf("%d",&x);
push(x);
}
else if(strcmp(str,"pop")==0)
{
//当栈空||队列为空的时候
if(top==0||front==back)
{
//这里采用的是标记,如果栈或者队列空了,就做出相应操作
//当然这里,也是我倒下瘫了好久的坑之所在
flag=0;
}
else
pop();
}
}
//这里就是不为空时的输出
if(flag==1)
{
while(front!=back)
{
printf("%d",queue[front++]);
if(front!=back)
printf(" ");
}
printf("\n");
for(n=0; top>=0; n++)
{
a[n]=stack[top];
num=n;
top--;
}
for(n=num; n>0; n--)
{
printf("%d",a[n]);
if(n!=1)
printf(" ");
}
printf("\n");
}
else
{
printf("error\nerror\n");
}
}
return 0;
}
//注意了,注意了:题目中虽然说只要在空栈,空队列时使用pop操作就会输出两行的error,一定只能由两个error,在空栈,空队列时,无论是多少个pop操作都只能输出两个error