看到这个问题,我现在的想到的解决方案是:
二个队列中,始终有一个队列(队列1)为空,另一个队列(队列2)为栈中的元素,入栈的操作就直接将元素放入队列2(所以栈满的条件就是队列2满),出栈时将队列2的元素依次出队并向队列1入队,直到队列2的最后一个元素,也就是栈顶的元素出栈。。。。此时队列1和队列2的次序和作用发生了一个翻转。。。。
要处理的细节情况还是比较多
比如push的时候,要处理最开始二个队列都为空的情况
核心代码:
struct stack
{
struct queue *q1;
struct queue *q2;
};
int initStack(struct stack* &s)
{
s = (struct stack*)malloc(sizeof(struct stack));
initQueue(s->q1);
initQueue(s->q2);
}
int isStackEmpty(struct stack *s)
{
if(isQueueEmpty(s->q1) && isQueueEmpty(s->q2))
return 1;
else
return 0;
}
int isStackFull(struct stack *s)
{
if(isQueueFull(s->q1) || isQueueFull(s->q2))
return 1;
else
return 0;
}
int push(struct stack *s,int e)
{
if(isStackFull(s))
return -1;
if(isStackEmpty(s))
{
enQueue(s->q1,e);
return 0;
}
if(isQueueEmpty(s->q1) && !isQueueEmpty(s->q2))
{
enQueue(s->q2,e);
return 0;
}
if(!isQueueEmpty(s->q1) && isQueueEmpty(s->q2))
{
enQueue(s->q1,e);
return 0;
}
else
return -1;
}
int copyQueue_until_onlyone(struct queue *srcQ,struct queue *destQ) //将一个队列srcQ(非空)拷贝到一个空的队列destQ,最后一个元素不copy而是作为返回值
{
int e;
while(!isQueueEmpty(srcQ))
{
deQueue(srcQ,e);
if(isQueueEmpty(srcQ))
{
return e;
}
enQueue(destQ,e);
}
}
int pop(struct stack *s,int &e)
{
if(isStackEmpty(s))
return -1;
if(isQueueEmpty(s->q1) && !isQueueEmpty(s->q2))
{
e = copyQueue_until_onlyone(s->q2,s->q1);
return 0;
}
if(!isQueueEmpty(s->q1) && isQueueEmpty(s->q2))
{
e = copyQueue_until_onlyone(s->q1,s->q2);
return 0;
}
else
return -1;
}
OVER!!!