-
#include<iostream>
using namespace std;
class Myqueue
{
public:
Myqueue(int capcaity);//初始化隊列
~Myqueue();
int get_length(); ?//獲取隊列元素個數
bool judge_empty(); ?//判斷隊列是否為空
bool judge_full(); ?//判斷隊列是否為滿
bool in_ele(int x); ? //入棧
bool out_ele(int &x); ?//出棧
void tra_ele(); ? //遍歷
void clear_queue(); ?//清空
private:
int m_length; ?//隊列元素個數
int m_capacity; ? // 隊列元素容量
int m_head; ? //隊列首部元素編號
int m_tail; ? // 隊列尾部元素編號
int *my_queue; ?//定義隊列指針
};
Myqueue::Myqueue(int capacity)
{
m_capacity = capacity;
my_queue = new int[m_capacity];
if (my_queue == NULL)
{
cout << "the applicatiao ofstorage for my_queue is failed" << endl;
}
m_head = 0;
m_tail = 0;
m_length = 0;
}
Myqueue::~Myqueue()
{
delete[]my_queue;
my_queue = NULL;
}
int Myqueue::get_length()
{
return m_length;
}
bool Myqueue::judge_empty()
{
if (m_length == 0)
{
cout << "the queue is empty" << endl;
return true;
}
return false;
}
bool Myqueue::judge_full()
{
if (m_length == m_capacity)
{
cout << "the queue is full"<<endl;
return true;?
}
return false;
}
bool Myqueue::in_ele(int x)
{
if (judge_full())
{
return false;
}
my_queue[m_tail] = x;
m_tail++;
m_length++;
if (m_tail == m_capacity)
m_tail = 0;
return true;
}
bool Myqueue::out_ele(int &x)
{
if (judge_empty())
{
return false;
}
x = my_queue[m_head];
m_head++;
m_length=m_length-1;
if (m_head == m_capacity)
m_head = 0;
return true;
}
void Myqueue::tra_ele()
{
int num = m_head;
for (int i = m_head; i<m_head+m_length; i++)
{
if (num == m_capacity)
{
num = 0;
? ?}
cout << my_queue[num] << endl;
num++;
}
}
void Myqueue::clear_queue()
{
m_head = 0;
m_tail = 0;
m_length = 0;
}
int main()
{
int out_ele;
Myqueue *lis =new Myqueue(5);
lis->in_ele(11);
lis->in_ele(12);
lis->in_ele(14);
lis->in_ele(8);
lis->in_ele(20);
lis->tra_ele();
cout << endl;
lis->out_ele(out_ele);
lis->tra_ele();
cout << endl;
lis->out_ele(out_ele);
lis->tra_ele();
cout << endl;
lis->in_ele(14);
lis->in_ele(8);
lis->tra_ele();
cout << endl;
lis->in_ele(20);
return 0;
}
查看全部 -
1.每次隊列插入一個新元素,隊列長度應該+1。m_iQueueLen++;
???每次隊列取出一個元素????,隊列長度應該-1。m_iQueueLne--;
2.對于環形隊列,經過一圈后又從0開始(因此要求 模%):
????入隊:m_ ihead =m_ ihead %m_ iQueuecapacity;
????出隊:m_itail? ?= m_i tail ??%m_iQueuecapacity;
????遍歷隊列時,是從隊頭開始遍歷的,而有時候隊頭不是指向位置0,指向其他位置?。另外,對于環形隊列,當遍歷完一圈后又從0開始。
?for(int i = 0; i <? m_iQueueLen; ++i)
????? ? cout << m_pQueue[(i+m_iHead)%m_iQueueCapacity] << endl;
????
查看全部 -
插入元素:每次插入之前需要判斷隊列是否已滿。插入元素從隊尾開始?????????????????????
?????????????????插入。每插入一個,隊尾指向下一個位置。
取出元素:每次取出之前需要判斷隊列是否為空。取出元素從隊頭開始
? ? ? ? ? ? ? ? ? 取出,每取出一個,隊頭指向下一個位置;
隊列中空出的位置,隊列為又可以插入新的元素
查看全部 -
05:47 初始化 申請內存
7:20 析構函數 銷毀隊列 內存回收
查看全部 -
數據結構是指相互之間存在一種或多種特定關系的數據元素的集合。
查看全部 -
隊列:
FIFO:first in first out
先進先出
查看全部 -
隊列:先入先出FIFO,分為普通隊列和環形隊列。普通隊列的空間利用沒有環形隊列充分,環形隊列的復雜度比普通隊列復雜。
查看全部 -
FIFO查看全部
-
環形隊列的聲明
查看全部 -
先入先出
普通隊列:浪費內存(不移動),處理速度慢(各位都前移一位)
環形隊列:充分利用內存空間
查看全部 -
環形隊列類聲明
查看全部 -
普通隊列示例
查看全部 -
隊列:先進先出 FIFO :first in first out
查看全部 -
MyQueue.cpp2
查看全部 -
MyQueue.cpp1
查看全部
舉報