注册 登录
编程论坛 C++教室

实现优先队列的入队运算

yingdi 发布于 2012-03-29 17:07, 459 次点击
实现优先队列的入队运算,部分代码如下。
//链表头文件说明
#ifndef __priorityLinkQueue__
#define __priorityLinkQueue__

//结点定义
#include <assert.h>
template <class ElemType>
struct linkNode
{
    int prior;
    ElemType data;
    linkNode<ElemType> *next;
};

//定义开始
#include <assert.h>
template <class ElemType>
class priorityLinkQueue
{
private:
    linkNode<ElemType> *front,*rear;
public:
    priorityLinkQueue();//初始化
    ~priorityLinkQueue();//销毁
    bool isEmpty();//判空,空为true
    void clear();//清空
    ElemType getFrontElem();//取队首
    void addElem(ElemType e,int prior);//入队
    void deleteElem();//出队
    void print();//打印
};

//实现
//初始化
template <class ElemType>
priorityLinkQueue<ElemType>::priorityLinkQueue()
{
    front=new linkNode<ElemType>;
    rear=front;
    front->next=0;
}
//销毁
template <class ElemType>
priorityLinkQueue<ElemType>::~priorityLinkQueue()
{
    clear();
    delete front;
    front=rear=0;
}
//判空,空为true
template <class ElemType>
bool priorityLinkQueue<ElemType>::isEmpty()
{
    if(front==rear)
        return true;
    return false;
}
//清空
template <class ElemType>
void priorityLinkQueue<ElemType>::clear()
{
    while(!isEmpty())
        deleteElem();
}
//取队首
template <class ElemType>
ElemType priorityLinkQueue<ElemType>::getFrontElem()
{
    assert(!isEmpty());
    return front->next->data;
}
//入队
template <class ElemType>
void priorityLinkQueue<ElemType>::addElem(ElemType e,int prior)
{
    需要实现的部分
}
//出队
template <class ElemType>
void priorityLinkQueue<ElemType>::deleteElem()
{
    需要实现的部分
}
//打印
template <class ElemType>
void priorityLinkQueue<ElemType>::print()
{
    if(isEmpty())
    {
        cout<<"空队"<<endl;
        return;
    }
    linkNode<ElemType> *currentNode;
    currentNode=front->next;
    while(currentNode)
    {
        cout<<currentNode->prior<<","<<currentNode->data<<"  ";
        currentNode=currentNode->next;
    }
    cout<<endl;
}


#endif

//主函数文件的代码如下
int main()
{
    priorityLinkQueue<int> Q=priorityLinkQueue<int>();
    for(int i=0;i<10;i++)
        Q.addElem(i+1,1);
    Q.addElem(11,2);
    Q.addElem(12,3);
    Q.addElem(13,2);
    Q.print();
    system("pause");
    return 0;
}

运行结果如下
3,12  2,11  2,13  1,1  1,2  1,3  1,4  1,5  1,6  1,7  1,8  1,9  1,10
0 回复
1