队列与模拟队列

队列与模拟队列,第1张

队列与模拟队列 队列 *** 作

题目描述:

队列(Queue),是一种线性存储结构。它有以下几个特点:

        (1) 队列中数据是按照"先进先出(FIFO, First-In-First-Out)"方式进出队列的。

        (2) 队列只允许在"队首"进行删除 *** 作(出队列),而在"队尾"进行插入 *** 作(入队列)。

队列通常包括的两种 *** 作:入队列 (push)和 出队列(pop)。

       乐乐班上有些同学想入队或出队,每次输入学生的学号和姓名,这个同学就入队,在输入一个数字n, 表示用队列中出队n个同学。队列初始为空。

输入:

        每行输入 入队学生的学号、姓名和出队学生的人数;输入EOF结束输入。

输出:

        出队学生的信息,包括学号和姓名结束输入后,输出队列中还有多少学生。

样例输入:

        10 yase 0 

        11 xiangyu 0

        12 anqila 1

        13 houyi 1

样例输出:

        10 yase

        11 xiangyu

        There are 2 students in the queue

# include 
# include 
# include 
using namespace std;
struct student
{
	int number;
	string name;
};
int main()
{
	queuea;
	queuec;
	student b;
	int n, m = 0;
	student* stu = new student[10];
	while (cin >> b.number >> b.name)
	{
		a.push(b);
		cin >> n;
		for (int i = 0; i < n; i++)
		{
			c.push(a.front());
			m++;
			a.pop();
		}
	}
	student* p;
	for (int i = 0; i < m; i++)
	{
		cout << c.front().number << " " << c.front().name << endl;
		c.pop();
	}
	cout << "There are " << a.size() << " students in the queue" << endl;
	return 0;
}
模拟队列 

题目描述: 

实现一个队列,队列初始为空,支持四种 *** 作:

    push x – 向队尾插入一个数 x;pop – 从队头d出一个数;empty – 判断队列是否为空;query – 查询队头元素。

现在要对队列进行 M个 *** 作,其中的每个 *** 作 3 和 *** 作 4 都要输出相应的结果。

输入格式:

        第一行包含整数 M,表示 *** 作次数。

        接下来 M 行,每行包含一个 *** 作命令, *** 作命令为 push x,pop,empty,query 中的一种。

输出格式:

        对于每个 empty 和 query  *** 作都要输出一个查询结果,每个结果占一行。

        其中,empty  *** 作的查询结果为 YES 或 NO,query  *** 作的查询结果为一个整数,表示队头元素的值。

数据范围:

        1≤M≤100000
        1≤x≤1000000000
        所有 *** 作保证合法。

输入样例:

10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6

输出样例:

NO
6
YES
4
# include 
# include 
using namespace std;
const int N = 100010;
int main()
{
	int m;
	int q[N], h = 1, t = 1;//h表示队头,t表示队尾
	cin >> m;
	string a;
	while(m--)
	{
		cin >> a;
		if(a=="push")
		{     // 向队尾插入一个数 x
			int x;
			cin >> x;
			q[t++] = x;
		}
		else if(a=="pop")
		{
			h++;//将队头往前移
		}
		else if(a=="query")
		{
			cout << q[h] << endl;
		}
		else if(a=="empty")
		{
			if(h>=t)//在上面代码中完成d出与插入都有h++、t++当h=t时,队尾已经被d出,所以为空。
		{
			cout << "YES" << endl;
		}
			else
			{
				cout << "NO" << endl;
			}
		}
	}
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5718669.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存