将栈和队列封装成模板类
栈:
#include <iostream>
#define N 128
using namespace std;
template <typename T>
class My_stack{
private:
T data[N];
int top;
public:
//无参构造
My_stack();
//判空
bool empty()const;
//入栈
void push(const T val);
//出栈
void pop();
//求栈中元素个数
int size();
//求栈顶元素
T& My_top();
//遍历
void show();
};
//无参构造
template <typename T>
My_stack <T>::My_stack():top(-1){}
//判空
template <typename T>
bool My_stack<T>::empty()const{
return top == -1?1:0;
}
//入栈
template <typename T>
void My_stack<T>::push(const T val){
if(top == N){cout<<"栈满"<<endl;return;}
top++;
data[top] = val;
}
//出栈
template <typename T>
void My_stack<T>::pop(){
if(empty()){cout<<"栈空"<<endl;return;}
data[top] = 0;
top--;
}
//求栈顶元素
template <typename T>
T& My_stack<T>::My_top(){
if(empty()){cout<<"栈空"<<endl;}
return data[top];
}
//求栈中元素个数
template <typename T>
int My_stack<T>::size(){
cout<<"栈中元素个数为:";
return top+1;
}
//遍历
template <typename T>
void My_stack<T>::show(){
if(empty()){cout<<"栈空"<<endl;return;}
for(int i=0;i<top+1;i++){
cout<<data[i]<<" ";
}
cout<<endl;
}
int main()
{
My_stack<int> s;
for(int i=0;i<10;i++){
s.push(i);
}
s.show();
cout<<s.size()<<endl;
cout<<"栈顶元素为:"<<s.My_top()<<endl;
for(int j=0;j<5;j++){
s.pop();
}
s.show();
cout<<s.size()<<endl;
cout<<"栈顶元素为:"<<s.My_top()<<endl;
return 0;
}
队列:
#include <iostream>
#define N 9
using namespace std;
template <typename T>
class My_queuse{
private:
T data[N];
int front,tail;
int len;
public:
//无参构造
My_queuse();
//判空
bool empty()const;
//判满
bool full()const;
//入队
void push(const T &val);
//出队
void pop();
//求队中元素个数
int size();
//求队头元素
T& My_front();
//遍历
void show();
};
//无参构造
template <typename T>
My_queuse<T>::My_queuse():front(0),tail(0),len(0){}
//判空
template <typename T>
bool My_queuse<T>::empty()const{
if(tail == front){
return true;
}
return false;
}
//判满
template <typename T>
bool My_queuse<T>::full()const{
if((tail+1)%N == front){
return true;
}
return false;
}
//入队
template <typename T>
void My_queuse<T>::push(const T &val){
if(full()){cout<<"队满"<<endl;return;}
data[tail] = val;
tail = (tail+1)%N;
len++;
}
//求队头元素
template <typename T>
T& My_queuse<T>::My_front(){
if(empty()){cout<<"队满"<<endl;}
return data[front];
}
//出队
template <typename T>
void My_queuse<T>::pop(){
if(empty()){return;}
data[front] = 0;
front = (front+1)%N;
len--;
return;
}
//队内元素个数
template <typename T>
int My_queuse<T>::size(){
return len;
}
//遍历
template <typename T>
void My_queuse<T>::show(){
if(empty()){return;}
int i = front;
while(1){
cout<<data[front]<<" ";
if((front+1)%N==tail){
break;
}
front = (front+1)%N;
}
front = i;
cout <<endl;
}
int main()
{
My_queuse<int> q;
for(int i=0;i<8;i++){
q.push(i+1);
}
q.show();
cout<<"队长为:"<<q.size()<<endl;
for(int j=0;j<4;j++){
q.pop();
}
q.show();
cout<<"队长为:"<<q.size()<<endl;
cout<<"队头元素:"<<q.My_front()<<endl;
return 0;
}