stack:先进后出
queue:先进先出
c++STL提供的函数:
stack:
empty()
pop() //删除栈首元素,返回void
push()
top() //返回栈首元素
swap(stack s) //交换两个栈元素
size() //元素个数
queue:
empty()
pop() //删除front()返回的元素,即队列中最老的元素
push()
front() //返回队列中最老的元素
back() //返回最新元素
size()
swap()
使用:
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int NUM=9;
template<class T>
struct node{
T val;
node *next;
};
template<class T>
class MyStack{
private:
node<T> *top;
public:
MyStack(){
top=NULL;
};
~MyStack(){
node<T> *temp = top;
while(temp!=NULL){
cout<<"delete:"<<temp->val<<endl;
node<T> *t = temp;
temp =temp->next;
delete t;
}
};
void push(const T &it){
node<T> *temp = new node<T>();
temp->val = it;
if(top==NULL){ //元素插入到链表首,符合先进后出的思想
temp->next = NULL;
top = temp;
}
else{
temp->next = top;
top = temp;
}
};
void pop(){
if(top == NULL){
cerr<<"empty stack."<<endl;
exit(-1);
}
node<T> *temp = top;
top = temp->next;
delete temp;
};
T gettop()const{
if(top==NULL){
cerr<<"empty stack."<<endl;
exit(-1);
}
return top->val;
};
int size()const{
int count=0;
node<T> *temp = top;
while(temp!=NULL){
count ++;
temp = temp->next;
}
return count;
};
bool empty()const{
return (top == NULL)?true:false;
};
friend ostream& operator << <T>(ostream& os,MyStack<T>& s); //带模板的友元函数声明
};
template<class T>
ostream& operator <<(ostream& os,MyStack<T> &s){
node<T> *temp = s.top;
while(temp!=NULL){
os<<temp->val<<" ";
temp = temp->next;
}
return os;
};
int main(){
// mystack
cout<<"-----mystack-----"<<endl;
MyStack<int> ms;
if(ms.empty()){
for(int i=0;i<NUM;i++)
ms.push(i);
}
cout<<ms<<endl;
cout<<"size:"<<ms.size()<<endl;
ms.pop();
cout<<"top="<<ms.gettop()<<endl;
/* STL stack
*
*/
cout<<"\n-----STL stack-------"<<endl;
stack<int> s,s2;
if(s.empty())
for(int i =0;i<NUM;i++){
s.push(i); //s :0-8
s2.push(8-i);
}
s2.push(9); //S2 0-9
//s.pop(); //删除top
cout<<"s.size:"<<s.size()<<endl;
while(!s2.empty()){
cout<<s2.top()<<' ';
s2.pop();
}
cout<<endl;
//s.emplace(4);
s.swap(s2); //交换s与s2
while(!s2.empty()){
cout<<s2.top()<<' ';
s2.pop();
}
/* 队列queue
* 先进先出:q.front()返回队列最前端的元素 q.pop()删除对前端元素
*/
cout<<"\n------STL queue------"<<endl;
queue<int> q,q2;
if(q.empty()){
for(int i =0;i<NUM;i++){
q.push(i); //s :0-8
//q2.push(8-i);
}
}
cout<<q.size()<<endl;
cout<<q.front()<<endl; //队列最前端元素(即最早入队列的元素)
cout<<q.back()<<endl; //队列末尾元素(最晚进队列元素)
//q.pop();
//q2.push(9);
//q.swap(q2);
cout<<endl;
}