每日一题
用两个队列实现栈
题目链接
![在这里插入图片描述](https://img-blog.csdnimg.cn/88b70c834b304ac4a7c55be40cf40636.png)
思路
- 这里主要讲怎么实现出栈StackPop操作
- 做完用两个栈实现队列,我们可能会想当然的认为,这一题也是一个主队列,一个辅助队列,当要出队时,首先判断辅助队列是否为空,如果是,那么就像《两个栈实现队列》一样,将主队列的所有元素逆序放入辅助队列中,但这种方法是行不通的,因为队列的原则是先进先出,元素只能从队尾入,从队头出,因此我们不能逆序弹出队列元素,只能按原来顺序弹出。
- 因此,我们就要改变辅助队列的用法
- 由于栈的性质是先入后出,队列的性质是先入先出,因此,如果要用队列来实现栈,那么如果要对这个栈进行出队操作,那么弹出的元素就应该是队列里的最后一个元素
- 所以,当要实现出栈时,我们可以先将主队列中除最后一个元素的所有元素全都放入辅助队列中,这时,主队列就只剩一个元素(即最后一个元素)了,我们将这个元素进行出队操作,即实现了出栈
- 最后,再将辅助队列的元素重新移回主队列,方便后续操作。
实现代码
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QueueNode;
typedef struct Queue
{
QueueNode* head;
QueueNode* tail;
}Queue;
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
}
void QueueDestroy(Queue* pq)
{
QueueNode* cur = pq->head;
while (cur)
{
pq->head = pq->head->next;
free(cur);
cur = pq->head;
}
pq->tail = NULL;
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
newnode->data = x;
newnode->next = NULL;
if (pq->tail == NULL && pq->head == NULL)
{
pq->head = newnode;
pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
void QueuePop(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
QueueNode* cur = pq->head;
pq->head = pq->head->next;
free(cur);
if (pq->head == NULL)
pq->tail = NULL;
}
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QDataType QueueBack(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
int QueueSize(Queue* pq)
{
QueueNode* cur = pq->head;
int size = 0;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
typedef struct {
Queue* q1, * q2;
} MyStack;
MyStack* myStackCreate() {
MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
obj->q1 = (Queue*)malloc(sizeof(Queue));
obj->q2 = (Queue*)malloc(sizeof(Queue));
QueueInit(obj->q1);
QueueInit(obj->q2);
return obj;
}
void myStackPush(MyStack* obj, int x) {
QueuePush(obj->q1, x);
}
int myStackPop(MyStack* obj) {
int size = QueueSize(obj->q1);
while (--size)
{
QueuePush(obj->q2, QueueFront(obj->q1));
QueuePop(obj->q1);
}
int result = QueueFront(obj->q1);
QueuePop(obj->q1);
size = QueueSize(obj->q2);
while (size--)
{
QueuePush(obj->q1, QueueFront(obj->q2));
QueuePop(obj->q2);
}
return result;
}
int myStackTop(MyStack* obj) {
return QueueBack(obj->q1);
}
bool myStackEmpty(MyStack* obj) {
return QueueEmpty(obj->q1);
}
void myStackFree(MyStack* obj) {
QueueDestroy(obj->q1);
}