理论基础 —— 队列 —— 链队列

【实现类】

template<class T>
struct Node{
    T data;
    Node *next;
};
template<class T>
class linkQueue{
public:
    linkQueue();
    ~linkQueue();
    void push(T x);//入队
    T pop();//出队
    bool empty();//判断队列是否为空
    T getFront();//获取队首元素
private:
    Node<T> *head,*tail;
};

【构造函数】

template <class T>
linkQueue<T>::linkQueue(){
    Node<T> s=new Node<T>;//创建一个头结点
    s->next=NULL;
    head=tail=s;//队首与队尾指针指向头结点
}

【析构函数】

template<class T>
linkQueue<T>::~linkQueue(){
    while(head!=NULL){
        Node<T> q=head;//暂存要被释放的结点
        head=head->next;//first指向要被释放的结点的下一个结点
        delete q;//删除结点
    }
}

【入队】

template <class T>
void linkQueue<T>::push(T x){//入队
    Node<T> s=new Node<T>;//新申请结点
    s->data=x;
    s->next=NULL;
    tail->next=s;//结点s插到队尾
    tail=s;
}

【出队】

template <class T>
T linkQueue<T>::pop(){//出队
    if(head==tail)
        throw "下溢";
    Node<T> p=new Node<T>;
    p=head->next;
    T x=p->data;//暂存出队结点
    head->next=p->next;
    if(p->next==NULL)//判断队列此时是否为空
        tail=head;
    delete p;
    return x;
}

【判断是否为空】

template<class T>
bool linkQueue<T>::empty(){//判断队列是否为空
    if(head==tail)
        return true;
    return false;
}

【获取队首元素】

template<class T>
T linkQueue<T>::getFront(){//获取队首元素
    if(head==tail)
        throw "下溢";
    return head->next->data;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值