栈和队列是两种具备特殊功能的数据结构,栈像是一个死巷子,数据进去后,先进去的数据反而没法出来,而后进去的数据却可以先出来,而队列就像排队一样,在队伍的尾端入,却需要在队伍的头部出。
栈的顺序结构类型定义:
template <class T>
class _Stack
{
public:
_Stack();
bool empty();
bool full();
int size();
void push(T &x);
void pop();
private:
T yuansu[100]; //分别为元素,栈首指针,栈的个数
int top;
int size;
};
构造函数:
template <class T>
_Stack<T>::_Stack(){
this->top = -1; //表示头部为空
this->size = 0; //表示元素为0
}
判断是否栈为空:
template<class T>
bool _Stack<T>::empty()
{
if (this->top == -1)
return true;
else
return false;
}
判断栈是否为满:
template<class T>
bool _Stack<T>::full(){
if (top>=100) {
return true;
}
else
return false;
}
求栈元素个数:
template <class T>
int _Stack<T>::getSize() {
return this->size;
}
插入元素:
template<class T>
void _Stack<T>::push(T & x){
if (top==99) {
cout<<"栈满"<< endl;
return;
}
else{
this->top++;
yuansu[top]=x;
this->size++;
return;
}
}
排除栈顶元素;
template <class T>
void _Stack<T>::pop() {
if (this->top==-1) {
cout<<"栈空"<<endl;
return ;
}else{
T x;
x=yuansu[this->top];
this->top--;
this->size--;
return;
}
}
这就是栈的顺序结构存储的基本方式了,用单链表无非就是记录一下根节点的位置就可以了,再记录一下队首节点位置,写法没什么困难,就不做赘述了。
队列元素基本定义:
template <class T>
class _queue
{
public:
_queue();
int Size();
void push(T &x);
void delete();
bool empty();
private:
T yuansu[100];
int front;
int rear;
int size;
};
构造函数:
template <class T>
_queue<T>::_queue(){
this->front=0;
this->front=0;
this->size=0;
}
获取元素数:
template<class T>
int _queue<T>::size(){
this->size =(rear-front+100)%100;
return size;
}
队尾插入元素:
template<class T>
void _queue<T>::push(T &x){
if ((rear+1)%100==front) {
cout<<"队列满"<<endl;
return;
}else {
yuansu[rear]=x;
rear=(rear+1)%100;
}
}
删除队首元素:
template<class T>
void _queue<T>::delete(){
if (front==rear) {
cout<<"队列为空"<<endl;
return;
}
T x;
x=yuansu[front];
this->front=(this->front+1)%100;
}
判断队列是否为空:
template<class T>
bool _queue<T>::empty() {
if(this->size==0)
return true;
return false;
}
这就是基本的队列的顺序存储的构成方式