数组模拟栈和队列

发布时间 2023-03-22 21:13:44作者: 风乐

https://www.acwing.com/problem/content/830/

https://www.acwing.com/problem/content/831/

相比数组模拟链表要简单的多,要注意的是tt的初始值,看个人习惯设置,栈一般为0,队列一般为1

//栈
#include<iostream>

using namespace std;

const int N = 100010;

int stk[N],tt;//栈值和栈顶指针,栈顶指针时刻指向栈顶元素下表
int m;
//插入
//stk[++t]=x
//删除
//tt--即可
//判空
//tt从1开始有值,tt<1时即空
//栈顶元素
//stk[tt]

void add(int x)
{
	stk[++tt]=x;//下标从1开始数
}

void remove()
{
	tt--;
}

void empty()
{
	if(tt>0)cout << "NO" << endl;
	else cout << "YES" << endl;
}

void query()
{
	cout << stk[tt] << endl;
}


int main()
{
	cin >> m;
	while(m--)
	{
		string op;
		cin >> op;
		if(op == "push")
		{
			int x;
			cin >> x;
			add(x);
		}
		else if(op == "pop")
		{
			remove();
		}
		else if(op == "empty")
		{
			empty();
		}
		else//qeury
		{
			query();
		}
	}
}

 

//队列
#include<iostream>

using namespace std;

const int N = 100010;

//在队尾插入元素,在队头弹出元素
int q[N],hh,tt=-1;//q表示队值,hh对头,tt队尾
int m;
//插入
//q[++tt]=x;
//弹出
//hh++;
//判空
//if(hh<=tt)not empty
//else empty
//队头队尾元素
//q[hh];
//q[tt];


void add(int x)
{
	q[++tt]=x;//下标从0开始数
}

void remove()
{
	hh++;
}

void empty()
{
	if(hh<=tt)cout << "NO" << endl;
	else cout << "YES" << endl;
}

void query()
{
	cout << q[hh] << endl;
}


int main()
{
	cin >> m;
	while(m--)
	{
		string op;
		cin >> op;
		if(op == "push")
		{
			int x;
			cin >> x;
			add(x);
		}
		else if(op == "pop")
		{
			remove();
		}
		else if(op == "empty")
		{
			empty();
		}
		else//qeury
		{
			query();
		}
	}
}