数据结构---栈和队列

栈和队列是两种具备特殊功能的数据结构,栈像是一个死巷子,数据进去后,先进去的数据反而没法出来,而后进去的数据却可以先出来,而队列就像排队一样,在队伍的尾端入,却需要在队伍的头部出。

栈的顺序结构类型定义:

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;
}
 

这就是基本的队列的顺序存储的构成方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值