用數組模擬棧與隊列

模擬棧

在這裏插入圖片描述

#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會快上一點點。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章