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

【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)

2015-05-31 22:57 281 查看
//【数据结构】用C++编写队列及基本操作(包括插入,出队列,摧毁,清空等等)

//头文件

#ifndef _SEQ_STACK_
#define _SEQ_STACK_

#include <iostream>
using namespace std;

template <class Type>
class Queue
{
public:
Queue(size_t sz = INIT_SIZE)
{
capacity = sz > INIT_SIZE ? sz : INIT_SIZE;
base = new Type[capacity];
front = back = 0;
}
~Queue()
{
destory();
}
public:

bool empty() const     //判断是否为空
{
return(front==back);
}

bool full()const       //判断是否已满
{
return((back+1)%capacity==front);
}

public:

void push(const Type &x)             //进队列
{
if (full())
{
cout << "队列已满,不能插入。" << endl;
return;
}
base[back] = x;
back = (back + 1) % capacity;
}

void pop()                          //出队列
{
if (empty())
{
cout << "队列为空" << endl;
return;
}
front=(front+1)%capacity;
}

bool getFront(Type &x) const             //获得队列头部
{
if (empty())
{
cout << "队列为空" << endl;
return false;
}
else
{
x = base[front];
return true;
}
}

int length() const                  //求大小
{
return back-front;
}

void clear()                       //清除
{
front=back=0;
}

void destory()                     //摧毁
{
delete[]base;
base = NULL;
capacity = front = back = 0;
}

void show() const                  //显示
{
if (empty())
{
cout << "队列为空" << endl;
return;
}
for (int i = front; i != back; i = (i + 1) % capacity)
{
cout << base[i] << endl;
}
}

void quit_system(int &x)
{
x = 0;
}

private:
enum { INIT_SIZE = 8 };
Type *base;
int capacity;
int front;
int back;
};

#endif

//主函数

#include "Queue.h"

void main()
{
Queue<int> myqueue;
int select = 1;
int Item;
while (select)
{
cout << "***************************************" << endl;
cout << "* [1] show            [2] push        *" << endl;
cout << "* [3] pop             [4] length      *" << endl;
cout << "* [5] clear           [6] destory     *" << endl;
cout << "* [7] getFront        [8] quit_system *" << endl;
cout << "***************************************" << endl;
cout << "请选择:>";
cin >> select;
switch (select)
{
case 1:
myqueue.show();
break;
case 2:
cout << "请输入要插入的值(-1结束):>";
while (cin >> Item, Item != -1)
{
myqueue.push(Item);
}
break;
case 3:
myqueue.pop();
break;
case 4:
cout << "大小为:" << myqueue.length() << endl;
break;
case 5:
myqueue.clear();
break;
case 6:
myqueue.destory();
break;
case 7:
if (myqueue.getFront(Item))
cout << "头元素为:"<<Item << endl;
else
cout << "该数不存在." << endl;
break;
case 8:
myqueue.quit_system(select);
break;
default:
break;
}
}
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: