#include <iostream>
#include <string>
using namespace std;
void push(int *queue, int num, int &end_index, int &queue_size, int queue_len)
{
if (queue_size == queue_len)
cout << "the queue is enough, please pop the data!" << endl;
else
{
queue[end_index] = num;
end_index = (end_index + 1 == queue_len ? 0 : end_index + 1);
++queue_size;
}
}
void pop(int *queue, int &start_index, int &queue_size, int queue_len)
{
if (queue_size == 0)
cout << "the queue is empty, please push the data!" << endl;
else
{
cout << endl << '\t' <<queue[start_index];
start_index = (start_index + 1 == queue_len ? 0 : start_index + 1);
--queue_size;
}
}
void peak(int *queue, int &start_index, int &queue_size)
{
if (queue_size == 0)
cout << "the queue is empty, please push the data!" << endl;
else
{
cout << endl << '\t' <<queue[start_index];
}
}
void show(int *queue, int start_index, int end_index, int queue_size, int queue_len)
{
if (queue_size == 0)
cout << "the queue is empty, please push the data!" << endl;
else
{
cout << endl;
while(start_index != end_index && queue_size != 0)
{
cout << queue[start_index] << ' ';
start_index = (start_index + 1 == queue_len ? 0 : start_index + 1);
--queue_size;
}
}
}
void ex_dao(int *queue1, int *queue2, int start_index, int end_index, int queue_size, int queue_len)
{
int end_index0 = end_index - 1 < 0? queue_len - 1 : end_index - 1;
int index1 = start_index, index2 = end_index0;
while(index1 != end_index && queue_size != 0)
{
queue2[index2] = queue1[index1];
index1 = (index1 + 1 == queue_len ? 0 : index1 + 1);
index2 = (index2 - 1 < 0? queue_len - 1 : index2 - 1);
}
}
int main()
{
int queue_len, num;
cout << "please input the length of the stack:" << '\t';
cin >> queue_len;
int *queue1 = new int [queue_len];
int *queue2 = new int [queue_len];
int start_index = 0, end_index = 0, queue_size = 0;//当前要存取数的位置
string str;
cout << endl << "input data. please select the method: push pop peak show exit: " << '\t';
while(cin >> str)
{
cout << endl;
if(str == "push")
{
cout << "please input the data: " << '\t';
cin >> num;
push(queue1 ,num , end_index, queue_size, queue_len);
}
else if(str == "pop")
{
ex_dao(queue1, queue2, start_index, end_index, queue_size, queue_len);
pop(queue2, start_index, queue_size, queue_len);
ex_dao(queue2, queue1, start_index, end_index, queue_size, queue_len);
}
else if(str == "peak")
{
ex_dao(queue1, queue2, start_index, end_index, queue_size, queue_len);
peak(queue2, start_index, queue_size);
ex_dao(queue2, queue1, start_index, end_index, queue_size, queue_len);
}
else if(str == "show")
show(queue1, start_index, end_index, queue_size, queue_len);
else if(str == "exit")
{
delete [] queue1;
delete [] queue2;
return 0;
}
else
cout << "try again" << endl;
cout << endl << "input data. please select the method: push pop peak exit: " << '\t';
}
system("pause");
return 0;
}
用队列实现栈(基于数组)
最新推荐文章于 2022-11-25 17:44:16 发布