用数组模拟栈与队列

文章目录

模拟栈

在这里插入图片描述

#include <iostream>
#include <string>

using namespace std;

const int N = 100010;
string s;
int n, stk[N], tt;
int main() 
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	cin >> n;
	while(n -- )
	{
		int x;
		cin >> s;
		if(s == "push")
		{
			cin >> x;
			stk[++ tt] = x;
		}
		else if(s == "pop") tt -- ;
		else if(s == "empty") cout << (tt < 0 ? "YES" : "NO") << endl;
		else cout << stk[tt] << endl;//取队头元素 
	}
	return 0;
}

模拟队列

在这里插入图片描述

#include <iostream>
#include <string>

using namespace std;

const int N = 100010;
string s;
int n, q[N], tt = -1, hh;
int main() 
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	cin >> n;
	while(n -- )
	{
		int x;
		cin >> s;
		if(s == "push")
		{
			cin >> x;
			q[++tt] = x;
		}
		else if(s == "pop") hh ++ ;
		else if(s == "empty") cout << (hh > tt ? "YES" : "NO") << endl;
		else cout << q[hh] << endl;//取队头元素 
	}
	return 0;
}

相对于C++STL会快上一点点。

发布了67 篇原创文章 · 获赞 216 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45895026/article/details/104341421