题目来自剑指Offer
题目:两个队列实现栈
思路:一个队列存数据,另一个队列作为转存数据的临时队列。
注意:哪个队列存数据不定,那个队列作为临时队列也不定。
压栈时:找到一个有数据的队列,放入数据。如果两个队列都为空,则随便找一个队列存数据。
出栈时:找到那个存数据的队列,设其数据个数为n。
(1)对数列执行 n-1 次出队操作。
(2)把这些出队的数据转存到另一个队列中。
(3)最后那个数据即为所求,输出。
栈满:一个队列满,则栈满。
栈空:两个队列都为空,则空。
代码:
#include <iostream>
#include <assert.h>
using namespace std;
const int SIZE = 5;
class Queue
{
public:
Queue();
void AddTail(int nData);
int RemoveHead();
bool IsFull();
bool IsEmpty();
int Length();
private:
int m_nFront;
int m_nRear;
int m_nArr[SIZE];
};
class Stack
{
public:
int Pop();
void Push(int nData);
bool IsEmpty();
bool IsFull();
int Length();
private:
Queue m_QueueOne;
Queue m_QueueTwo;
};
Queue::Queue()
{
m_nFront = m_nRear = 0;
}
void Queue::AddTail(int nData)
{
if (IsFull())
{
cout<<"队列已满!"<<endl;
return;
}
else
{
m_nArr[(m_nRear++)%SIZE] = nData;
}
}
int Queue::RemoveHead()
{
if (IsEmpty())
{
cout<<"队列空!"<<endl;
return -1;
}
else
{
return m_nArr[(m_nFront++)%SIZE];
}
}
bool Queue::IsFull()
{
if ((m_nRear + 1) % SIZE == m_nFront)
{
return true;
}
else
{
return false;
}
}
bool Queue::IsEmpty()
{
if (m_nFront == m_nRear)
{
return true;
}
else
{
return false;
}
}
int Queue::Length()
{
return (m_nRear - m_nFront + SIZE) % SIZE;
}
//**************STACK***********************
//弹出操作:
//对于有数据的队列:
// 先把队列中除最后一个元素外的数据依次放入另一个队列中
// 把该队列中最后一个元素返回,此时该队列为空队列
int Stack::Pop()
{
int nData = -1;
assert((m_QueueOne.IsEmpty() && !m_QueueTwo.IsEmpty()) || (m_QueueTwo.IsEmpty() && !m_QueueOne.IsEmpty()));
if (!m_QueueOne.IsEmpty())//队列1中有元素
{
while (m_QueueOne.Length() > 1)
{
nData = m_QueueOne.RemoveHead();
m_QueueTwo.AddTail(nData);
}
return m_QueueOne.RemoveHead();
}
else
{
while (m_QueueTwo.Length() > 1)
{
nData = m_QueueTwo.RemoveHead();
m_QueueOne.AddTail(nData);
}
return m_QueueTwo.RemoveHead();
}
}
//入栈操作:
//找到一个有数据的队列压入数据。
//两个队列都为空,随便找一个队列压入数据
void Stack::Push(int nData)
{
assert((!m_QueueOne.IsFull() && m_QueueTwo.IsEmpty())
|| m_QueueOne.IsEmpty() && !m_QueueTwo.IsFull());
if (m_QueueOne.IsEmpty())
{
m_QueueTwo.AddTail(nData);
}
else
{
m_QueueOne.AddTail(nData);
}
}
int Stack::Length()
{
assert(m_QueueOne.IsEmpty() || m_QueueTwo.IsEmpty());
if (m_QueueOne.IsEmpty())
{
return m_QueueTwo.Length();
}
else
{
return m_QueueOne.Length();
}
}
bool Stack::IsEmpty()
{
assert(m_QueueOne.IsEmpty() || m_QueueTwo.IsEmpty());
if (m_QueueOne.IsEmpty() && m_QueueTwo.IsEmpty())
{
return true;
}
else
{
return false;
}
}
bool Stack::IsFull()
{
assert(m_QueueOne.IsEmpty() || m_QueueTwo.IsEmpty());
if (m_QueueOne.IsFull() || m_QueueTwo.IsFull())
{
return true;
}
else
{
return false;
}
}
int main()
{
Stack s;
cout<<"push: ";
for (int i = 0;i < SIZE - 1;i++)
{
cout<<i<<" ";
s.Push(i);
}
cout<<endl<<"pop: ";
cout<<s.Pop()<<endl;
cout<<"push: ";
if (!s.IsFull())
{
cout<<10<<" ";
s.Push(10);
}
else
{
cout<<"已满!"<<endl;
}
cout<<endl<<"push: ";
if (!s.IsFull())
{
cout<<20<<" ";
s.Push(20);
}
else
{
cout<<"已满!"<<endl;
}
cout<<endl<<"pop: ";
while (!s.IsEmpty())
{
cout<<s.Pop()<<" ";
}
cout<<endl;
system("pause");
return 1;
}