在华为遇到的一个面试题
前阵子在华为面试时碰到一个问题当时没有解决,现在提出来请各位高手指点一下
有两个栈(已经提供了一下函数):
instack() 入栈;
outstack() 出栈;
isempty() 是否为空;
isfull() 是否已满;
要求用两个栈()实现一个通用的队列的如下操作:
inqueue() 入栈;
outqueue() 出栈;
isempty() 是否为空;
isfull() 是否已满;
[解决办法]
CStack a, b;
BOOL CList::isempty()
{
return a.isempty()&&b.isempty();
}
BOOL CList::isfull()
{
return a.isfull();
}
void CList::inqueue(T t)
{
if(!isfull())
a.inqueue(t);
}
T void CList::outstack()
{
if(!isempty())
{
if(b.isempty())
{
while(!a.isempty() && !b.isfull())
{
b.inqueue(a.outstack);
}
if(!b.isempty())
return b.outstack();
}
else
{
return b.outstack();
}
}
return NULL;
}
有一个要求,b栈要比a栈长,否则在处理while(!a.isempty() && !b.isfull())时虽然不会crash,但是结果会不对.a栈的内容无法全部压到b栈中.
[解决办法]
class Q
{
private:
stack <int> a;
stack <int> b;
public:
bool inqueue(int data);
int outqueue(void);
bool isempty(void);
bool isfull(void);
};
bool Q::isempty(void)
{
return a.empty();
}
bool Q::isfull(void)
{
return a.size() > 10;
}
int Q::outqueue(void)
{
int tNum = a.top();
a.pop();
return tNum;
}
bool Q::inqueue(int data)
{
if(a.size() > 10 || a.size() < 1)
return false;
while(!a.empty())
{
b.push(a.top());
a.pop();
}
b.push(data);
while(!b.empty())
{
a.push(b.top());
b.pop();
}
return true;
}