您的位置:首页 > 理论基础 > 数据结构算法

数据结构课后题目源码

2016-05-20 17:32 423 查看
习题描述如下:

       假设以数组Q[m]存放循环队列中的元素,同时设置一个标志tag,以tag==0和tag==1来区别在队头指针(front)和队尾指针(rear)相等时,队列状态为“空”还是为”满“。试编写与此结构相应的插入(EnQueue)和删除(DeQueue)算法。

以下是博主自己码的代码,不喜勿喷!

#ifndef QUEUE_H_
#define QUEUE_H_
#include <iostream>

using namespace std;

template<class T>
class Queue{
private:
int front,rear;
T * elements;
int maxSize;
int tag;
public:
Queue(int sz = 10);
~Queue();
bool EnQueue(const T & x);
bool DeQueue(T & x);
};

template<class T>
Queue<T>::Queue(int sz)
{
maxSize = sz;
tag = 0;
elements = new T[maxSize];
front = rear = 0;
}

template<class T>
Queue<T>::~Queue()
{
delete[] elements;
}

template<class T>
bool Queue<T>::EnQueue(const T & x)
{
if (front == rear&&tag == 1)
{
cout << "The queue is full!" << endl;
return false;
}
elements[rear] = x;
rear = (rear + 1) % maxSize;
tag = 1;
return true;
}

template<class T>
bool Queue<T>::DeQueue(T & x)
{
if (front == rear&&tag == 0)
{
cout << "The queue is empty!" << endl;
return false;
}
x = elements[front];
front = (front + 1) % maxSize;
tag = 0;
return true;
}
#endif


// ex3-23.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Queue.h"

int _tmain(int argc, _TCHAR* argv[])
{
Queue<int> queue(5);
int j;
queue.DeQueue(j);
int x = 5;
for (int i = 0; i < 5; i++)
{
queue.EnQueue(x);
}
int y = 6;
queue.EnQueue(y);
system("pause");
return 0;
}


谢谢阅读!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 数据结构 源码