链式队列

队列的另一种存储方式是链表,可以用带头结点的单链表来表示;队列的头指针front指向单链表的头结点,队列的尾指针rear指向单链表的最后一个节点。
出队就是删除第一个元素节点,入队就是在表维增加一个节点;其中链表式的队列模版中有两个数据成员,分别是队头指针front和队尾指针rear,其初始值都指向头节点,头节点后没有元素,表示空队列;
简单实现了下

#ifndef NODE_h
#define NODE_h
#define NULL 0
template<class T>
struct Node{
    Node<T>* next;
    T data;
    Node(){
        next=NULL;
    }
    Node(T e,Node<T>* p=NULL){
        next=p;
        data=e;

    }
};
#endif

#ifndef GUARD_SEQQUEUE_h
#define GUARD_SEQQUEUE_h
#include"Node.h"
#include<iostream>
#include<cassert>
template<class T>
class SeqQueue{
public:
    explicit SeqQueue();
    virtual ~SeqQueue();
    //判断队空
    bool IsEmpty()const;
    //元素个数
    int GetLength()const;
    //入队
    void EnQueue(const T& e);
    //出队
    T DelQueue();
    //取对头元素
    T GetFront();
    //清空队列
    void Clear();

private:
    //链式存储不需要考虑长度,也不需要数据元素,这些可以通过Node去构造
    Node<T>* front;
    Node<T>* rear;  
};


template<class T>
SeqQueue<T>::SeqQueue(){
    front=rear=new Node<T>;
}

//销毁链式队列中所有的节点,并释放头节点
template<class T>
SeqQueue<T>::~SeqQueue (){
    Clear();
    delete front;
}

template<class T>
int SeqQueue<T>::GetLength()const{
    Node<T>* p=front->next;
    int count=0;
    for(p;p!=NULL;p->next){
        ++count;
    }
    return count;
}
//头结点后没有元素节点表示队空
template<class T>
bool SeqQueue<T>::IsEmpty()const{
    return front->next==NULL;
}

//入队:先加节点,再移动rear指针
template<class T>
void SeqQueue<T>::EnQueue(const T& e){
    Node<T>* p;
    p=new Node<T>(e,NULL);
    rear->next=p;
    rear=rear->next;

}

//出队
template<class T>
T SeqQueue<T>::DelQueue(){
       assert(!IsEmpty());
        T e;
        Node<T>* p=front->next;
        e=p->data;
        front->next=p->next;
        delete p;
       return e;

}

//取队头元素
template<class T>
T SeqQueue<T>::GetFront(){
    assert(!IsEmpty());
    T e;
    e=front->next->data;
    return e;
}
//清空列表,只保留头结点,并且使头指针和尾指针都指向头节点
template<class T>
void SeqQueue<T>::Clear(){
    Node<T>* p=front->next;
    while(p!=NULL){
        front->next=p->next;
        delete p;
        p=front->next;
    }
    rear=front;
}

#endif


#include"SeqQueue.h"
#include<iostream>
using namespace std;

int main(){
    int i;
    SeqQueue<char> que;                          //构造一个空链队
    char str1[]="abcdefghijklmnop";           //17个元素,包括串结束符
    for(i=0;i<17;i++) que.EnQueue(str1[i]);
    for(i=0;i<17;i++) cout<<que.DelQueue();           //先进先出
    cout<<endl; 
    if(que.IsEmpty()) cout<<"队空"<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值