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

数据结构:栈和列之如何用两个队列实现一个栈?两个栈实现一个队列?

2017-07-19 23:44 411 查看
1、栈和队列分析

栈是一种特殊的线性表。其特殊性在于限定插入和删除数据元素的操作只能在线性表的一端进行

队列(Queue)也是一种运算受限的线性表,它的运算限制与栈不同,是两头都有限制,插入只能在表的一端进行(只进不出),而删

除只能在表的另一端进行(只出不进),允许删除的一端称为队尾(rear),允许插入的一端称为队头 (Front)。

2、两个队列实现一个栈:利用队列先进先出的特性,在队列一队头中插入一系列数据,只能从队尾删除数据,而此时再定义队列二,

把队列一先进入队列的数据存放在队列二,然后删除队列一最新插入的数据,从而模拟实现栈先插入进来的数据先出栈的功能。

//两个队列实现一个栈
/*
template<class T>
class CStack
{
public:
void appendHead(const T&x) //从栈顶插入元素
{
q1.push(x);
}
T deleteTail() //从栈顶删除元素
{
if (q2.size() <= 0)
{
while (q1.size()-1)
{
T value = q1.front();
q1.pop();
q2.push(value);
}
}

T tail = q1.front();
q1.pop();
return tail;
}
private:
queue<T> q1;
queue<T> q2;
};

//测试
void main()
{
CStack<int> st;
st.appendHead(5);
st.appendHead(2);
st.appendHead(3);
st.appendHead(9);
st.appendHead(3);
st.appendHead(2);

cout << st.deleteTail() << endl;
}
*/

2、两个栈实现一个队列:道理和两个队列实现一个栈的原理类似,在此不再赘述

//两个栈实现一个队列
//栈:先进后出
//队列:先进先出

template<class T>
class TwoQueue
{
public:
TwoQueue()
{}

void In_Queue(const T&x) //从队尾插入数据
{
s1.push(x);
}
T Out_Queue()
{
if (s2.size() == 0)
{
while (!s1.empty())
{
T value=s1.top();
s1.pop();
s2.push(value);
}
}

if (s2.size() > 0)
{
T head = s2.top();
s2.pop();
return head;
}
else
{
return NULL;
}
}
T Front_Queue()
{
if (s2.size() > 0)
{
T head = s2.top();
return head;
}
else
{
return NULL;
}
}
size_t Empty_Queue()
{
return (s2.size()==0);
}

private:
stack<T> s1;
stack<T> s2;
};

int main()
{
TwoQueue<int> tq;
tq.In_Queue(1);
tq.In_Queue(2);
tq.In_Queue(3);
tq.In_Queue(4);

cout << tq.Out_Queue() << endl;
cout << tq.Out_Queue() << endl;

cout<<tq.Front_Queue()<< endl;
cout<<tq.Empty_Queue() <<endl;

cout << tq.Out_Queue() << endl;
cout << tq.Out_Queue() << endl;

cout<<tq.Empty_Queue() <<endl;

system("pause");
return 0;
}

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息