栈
cpp
#include <iostream>
#include<vector>
using namespace std;
template<typename T>
class my_stack
{
private:
vector<T> *data;
public:
my_stack() :data(new vector<T>()){}
~my_stack(){delete data;};
bool empty();
//入栈
void push(int a);
void pop();
//栈顶
int top();
//栈大小
size_t size();
};
template<typename T>
bool my_stack<T>::empty()
{
cout<<"栈为空栈"<<endl;
return data->empty();
}
template<typename T>
void my_stack<T>::push(int a){
data->push_back(a);
cout<<"入栈成功"<<endl;
}
template<typename T>
void my_stack<T>::pop(){
if(data->empty()==0)
{
cout<<"出栈:"<<(int)data->back()<<endl;
data->pop_back();
return;
}
cout<<"栈为空栈"<<endl;
return;
}
template<typename T>
//栈顶
int my_stack<T>::top(){
if(data->empty()==0)
{
return data->back();
}
std::cout<<"栈为空栈"<<std::endl;
return 0;
}
template<typename T>
//栈大小
size_t my_stack<T>::size(){
return data->size();
}
int main()
{
my_stack <int>s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.pop();
cout<<"top:"<<s.top()<<endl;
s.pop();
s.pop();
s.pop();
cout<<"栈大小:"<<s.size()<<endl;
s.empty();
return 0;
}
队列
cpp
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class my_queue
{
private:
vector <T>*data;
public:
my_queue() :data(new vector<T>){}
~my_queue(){delete data;}
bool empty();
//入队
void push(int a);
//出队
void pop();
//队头
int top();
//队大小
size_t size();
};
template <typename T>
bool my_queue<T>::empty()
{
cout<<"队列为空队"<<endl;
return data->empty();
}
//入队
template <typename T>
void my_queue<T>::push(int a){
data->push_back(a);
cout<<data->back()<<"入队成功:"<<endl;
}
//出队
template <typename T>
void my_queue<T>::pop(){
if(data->empty()==0)
{
cout<<"出队:"<<data->front()<<endl;
data->erase(data->begin());
}
else
{
cout<<"队列为空队"<<endl;
}
return;
}
//队头
template <typename T>
int my_queue<T>::top(){
if(data->empty()==0)
{
return data->front();
}
std::cout<<"队列为空队"<<std::endl;
return 0;
}
//队大小
template <typename T>
size_t my_queue<T>::size(){
return data->size();
}
int main()
{
my_queue<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout<<"队大小:"<<s.size()<<endl;
s.pop();
cout<<"top:"<<s.top()<<endl;
s.pop();
s.pop();
s.pop();
cout<<"队大小:"<<s.size()<<endl;
s.empty();
return 0;
}