C ++ in stack and queue

First, stacks and stack

Stack is one of the basic data structure, characterized by: "last out."
Header: #include <stack>
on the operation of the stack:

stack< Type >a;		//定义栈,Type为数据类型,例如int、float、char
s.push(x);		//把x放到栈顶
s.top();		//返回栈顶的元素,但不会删除
s.pop();		//删除栈顶的元素,但不会返回,在出栈时需要进行两步操作
			//即先top()获得栈顶元素,再pop()删除栈顶元素
s.size();		//返回栈中元素的个数
s.empty();		//检查栈是否为空,如果为空,返回true,否则返回false			

Simple to achieve this:

#include<bits/stdc++.h>
#include<stack>	//可以不写
using namespace std;
int main()
{
	 stack<int>s;
	 int i;
	 for(i=1;i<=6;i++)
	  s.push(i);
	 cout<<"栈中元素共"<<s.size()<<"个"<<endl;
	 cout<<"栈顶元素为"<<s.top()<<endl;
	 s.pop();
	 cout<<"栈中目前元素为:";
	 while(!s.empty()){
	  s.top();
	  cout<<s.top()<<" ";
	  s.pop(); 
	 } 
	 return 0
}

Achieve results:
Here Insert Picture Description

Second, the queue and the queue

Queue is one of the basic data structure, is characterized by "first in first out."
Header: #include <queue>
on the operation queue:

queue< Type >q;		//定义栈,Type为数据类型,例如int、float、char
q.push(x);		//把x放进队列
q.front();		//返回队首元素,但不会删除
q.pop();		//删除队首元素
q.back();		//返回队尾元素
q.size();		//返回元素个数
q.empty();		//检查队列是否为空

Simple implementation:

#include<bits/stdc++.h>
#include<queue> //可以不写
using namespace std;
int main(){
	 queue<int>q;
	 for(int i=0;i<=6;i++)
	  q.push(i);
	 cout<<"队列中元素个数为:"<<q.size()<<endl; 
	 cout<<"队首元素是:"<<q.front()<<endl;
	 q.pop(); //删除队首元素 
	 cout<<"队尾元素是:"<<q.back()<<endl;  
	 while(!q.empty()){ //若队列不为空,返回队首元素 
	  cout<<q.front()<<" ";
	  q.pop(); //删除队首元素 
	 } 
	 return 0;
}

Achieve results:

Here Insert Picture Description

Published 34 original articles · won praise 85 · views 4617

Guess you like

Origin blog.csdn.net/weixin_45895026/article/details/103960993