-->
当前位置:首页 > 题库 > 正文内容

7-5 队列操作 (10 分)

Luz4年前 (2021-03-08)题库2592
7-5 队列操作 (10 分)

请实现一个MyQueue类,实现出队,入队,求队列长度.

实现入队函数 void push(int x); 实现出队函数 int pop(); 实现求队列长度函数 int size();

输入格式:

每个输入包含1个测试用例。每个测试用例第一行给出一个正整数 n (n <= 10^6) ,接下去n行每行一个数字,表示一种操作: 1 x : 表示从队尾插入x,0<=x<=2^31-1。 2 : 表示队首元素出队。 3 : 表示求队列长度。

输出格式:

对于操作2,若队列为空,则输出 “Invalid”,否则请输出队首元素。 对于操作3,请输出队列长度。 每个输出项最后换行。

输入样例:

5
3
2
1 100
3
2

输出样例:

0
Invalid
1
100
作者
司广涛
单位
曲阜师范大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<iostream> 
using namespace std;
typedef struct queue{
	int x;
	struct queue *next;
} LinkList;
class  MyQueue{
	LinkList *head, *node, *end; 
	static int j;
	public:
		MyQueue()
		{
			head=NULL; 
			node=NULL;
			end=NULL; 
			head=new LinkList;
			end=head;
			
		}
		void push(int x)
		{
	    	node=new LinkList;
			node->x=x;
			end->next=node;
			node=end; 
			j++;
		}
		void pop()
		{
			if(j==0)
		    	cout<<"Invalid"<<endl;
			else
			     {
			     	cout<<head->next->x<<endl;
			     	head->next=head->next->next;
			     	delete head->next;
		        	j--;
				 }
		}
		int size()
		{
			return j;
		}
};
int MyQueue::j=0;
int main(void)
{
	MyQueue a;
	int n,i,c,d;
	scanf("%d",&n); 
	for(i=0;i<n;i++)
	{
		scanf("%d",&c);
		
		if(c==1)
		{
			scanf("%d",&d);
			a.push(d);
		}
		else if(c==2){
			a.pop();
		}
		else if(c==3){
			cout<<a.size()<<endl;
		}
		
	}
}


发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。