栈与队列

栈stack
C++ 栈stack的头文件为:
#include
c++ stl栈stack的成员函数介绍
操作 比较和分配堆栈
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素

队列queue
C++队列Queue类成员函数如下:
back()
返回最后一个元素
empty()
如果队列空则返回真
front()
返回第一个元素
pop()
删除第一个元素
push()
在末尾加入一个元素
size()
返回队列中元素的个数

经典例题


HRBUST - 1182

#include <cstdio>
#include <cstring>
#include <stack> 
using namespace std; 
int a[50];
int b[50]; 
int main(){   
	int n;    
	while(scanf("%d", &n) != EOF){ 
		for(int i=0;i<n;i++){
			scanf("%d",&b[i]);
			a[i]=i+1;
		}                        
		stack<int> q;              
		int j = 0;       
		for(int i = 0; i < n; i++){            
			q.push(a[i]);                      
			while(!q.empty() && q.top() == b[j]){                              
				q.pop();                
				j++;           
			}       
		}        
		if(j != n){            
			printf("No\n");        
		}         
		else{
			printf("Yes\n");
		} 
	}  
	return 0;
}

队列
HRBUST - 1940

#include<iostream>
#include<queue>
#include<string>
using namespace std;
int main()
{
	int n, x;
	string str;
	while (cin >> n)
	{
		queue<int>q;
		for (int i = 0; i < n; i++)
		{
			cin >> str;
			if (str[0] == 'e')
			{
				cin >> x;
				q.push(x);
			}
			else if (str[0] == 'q')
			{
				if (q.empty())
					cout << "this is empty!" << endl;
				else
				{
					while (!q.empty())
					{
						cout << q.front() << endl;
						q.pop();
					}
				}
			}
			else if (str[0] == 'd')
			{
				if (q.empty())
					cout << "this is empty!" << endl;
				else
				{
					cout << q.front() << endl;
					q.pop();
				}
			}
		}
		cout << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值