您的位置:首页 > 编程语言 > C语言/C++

队列的链式存储结构C++实现

2015-03-24 15:59 423 查看
采用单链表实现队列,实质上为单链表的一种简化。只需要在链表的头部删除和尾部加入元素即可

/*************************************************************************
> File Name: LinkQueue.cpp
> Author: Shorey
> Mail: shoreybupt@gmail.com
> Created Time: 2015年03月24日 星期二 15时31分18秒
************************************************************************/

#include<iostream>
using namespace std;

struct Node
{
int data;
Node *next;
};

class LinkQueue
{
public:
LinkQueue(); //构造函数,初始化一个空队列
~LinkQueue(); //析构函数,释放队列中的结点
void EnQueue(int x); //把元素x入队
int DeQueue(); //把队头元素出队
int GetQueue() //获取队头元素,但不删除
{
if(front!=rear) //判断队列不为空
return front->next->data;
}
bool Empty() //判断队列是否为空
{
if(front==rear) return 1;
else return 0;
}
private:
Node *front,*rear;
};

LinkQueue::LinkQueue()
{
front=new Node;
front->next=NULL;
rear=front;
}

LinkQueue::~LinkQueue()
{
Node *p=front;
while(!front)
{
front=front->next;
delete p;
p=front;
}
}

void LinkQueue::EnQueue(int x)
{
Node *s=new Node;
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
}

int LinkQueue::DeQueue()
{
if(!Empty())
{
Node *p=front->next;
int x;
front->next=p->next;
x=p->data;
delete p;
return x;
}
}

int main()
{
LinkQueue s;
s.EnQueue(4);
s.EnQueue(6);
s.EnQueue(7);
cout<<s.DeQueue()<<endl;
cout<<s.GetQueue()<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 数据结构