栈
#include <iostream>
using namespace std;
template<class T>
class MyStack
{
private:
int top;//栈顶
int size;//栈的容量
T* data;//数据
public:
//无参构造
MyStack()
{
this->top = -1;
this->size = 0;
this->data = nullptr;
}
//有参构造
MyStack(int size)
{
this->top = -1;
this->size = size;
this->data = new T[size];
}
//析构
~MyStack()
{
if(this->data != nullptr)
{
delete []this->data;
}
}
//判空
bool empty()
{
return this->top == -1;
}
//判满
bool full()
{
return this->top == this->size-1;
}
//入栈
void push_stack(T data)
{
if(this->full())
{
cout << "栈已满,入栈失败" << endl;
}else
{
this->data[++this->top] = data;
cout << data << " 入栈成功" << endl;
}
}
//出栈
void pop_stack()
{
if(this->empty())
{
cout << "空栈,出栈失败" << endl;
}else
{
cout<< "出栈成功 " << this->data[this->top--]<<endl;
}
}
};
测试代码:
int main()
{
MyStack<int> st(10);
for(int i=1; i<=11; i++)
{
st.push_stack(i);
}
for(int i=0; i<12; i++)
{
st.pop_stack();
}
return 0;
}
结果:
1 入栈成功
2 入栈成功
3 入栈成功
4 入栈成功
5 入栈成功
6 入栈成功
7 入栈成功
8 入栈成功
9 入栈成功
10 入栈成功
栈已满,入栈失败
出栈成功 10
出栈成功 9
出栈成功 8
出栈成功 7
出栈成功 6
出栈成功 5
出栈成功 4
出栈成功 3
出栈成功 2
出栈成功 1
空栈,出栈失败
空栈,出栈失败
队列:
#include <iostream>
using namespace std;
template <typename T>
class MyQueue
{
private:
int head;//头下标
int tail;//尾下标
int size;//容量
T* data;//数据
public:
//无参构造
MyQueue()
{
this->head = 0;
this->tail = 1;
this->data = nullptr;
}
//有参构造
MyQueue(int size)
{
this->head = 0;
this->tail = 1;
this->size = size;
this->data = new T[size];
}
//析构
~MyQueue()
{
if(this->data != nullptr)
{
delete []this->data;
}
}
//判空
bool empty()
{
return (this->head+1)%this->size == this->tail;
}
//判满
bool full()
{
return this->tail == this->head;
}
//入队
void push(T& data)
{
if(this->full())
{
cout << "队已满,入队失败" <<endl;
}else
{
this->data[this->tail] = data;
this->tail = (this->tail+1)%size;
cout << data << " 入队成功" << endl;
}
}
//出队
void pop()
{
if(this->empty())
{
cout << "空队列,出队失败" <<endl;
}else
{
this->head = (this->head+1)%size;
cout << this->data[this->head] << " 出队成功" << endl;
}
}
};
测试代码:
int main()
{
MyQueue<int> mq(11);
for(int i=1; i<=11; i++)
{
mq.push(i);
}
for(int i=0; i<11; i++)
{
mq.pop();
}
return 0;
}
测试结果:
1 入栈成功
2 入栈成功
3 入栈成功
4 入栈成功
5 入栈成功
6 入栈成功
7 入栈成功
8 入栈成功
9 入栈成功
10 入栈成功
栈已满,入栈失败
出栈成功 10
出栈成功 9
出栈成功 8
出栈成功 7
出栈成功 6
出栈成功 5
出栈成功 4
出栈成功 3
出栈成功 2
出栈成功 1
空栈,出栈失败
空栈,出栈失败