用两个队列实现一个后进先出的栈,并支持普通栈的全部四种操作:push、pop、top和empty。本oj题出自leetcode平台,用于学习交流。
一、定义结构
//队列的结构
typedef struct QueueNode {
struct QueueNode* next;
int data;
} QueueNode;
typedef struct Queue {
QueueNode* head;//队头
QueueNode* tail;//队尾
} Queue;
//栈的结构
typedef struct MyStack {
Queue q1;//队列1
Queue q2;//队列2
} MyStack;
二、栈的创建
对栈进行初始化就是将两个队列的队头队尾置空,栈的空间在接口内malloc创建,创建完成后将指向栈空间的指针作为返回值返回。
MyStack* myStackCreate() {
MyStack* stack = malloc(sizeof (MyStack));
stack->q1.head = stack->q1.tail = NULL;
stack->q2.head = stack->q2.tail = NULL;
return stack;
}
三、实现Push和Pop接口
基本思路:让其中一个队列保持空的状态。每次push(进栈)时将数据放入不为空的队列(如果两个队列都为空,则任选其一放入数据)。每次pop(出栈)时,将不为空的队列中队尾之前的数据依次出队并放入空队列,此时不为空的队列中只剩下一个数据,释放该数据的空间就是对栈进行出栈操作。
按照该思路,大致作图如下:
![](https://img-blog.csdnimg.cn/9f8257867d07463f9e1705d2e925f43f.png)
代码实现:
void myStackPush(MyStack* obj, int x) {
Queue* dest;
//选择其中有数据的队列插入数据 如果两个队列都没数据 则插入到q2
if (obj->q1.head != NULL)
dest = &obj->q1;
else
dest = &obj->q2;
if (dest->head == NULL)//dest指向的队列为空(第一次放数据)
{
dest->head = dest->tail = malloc(sizeof (QueueNode));
dest->tail->data = x;
dest->tail->next = NULL;
}
else
{
dest->tail->next = malloc(sizeof (QueueNode));
dest->tail = dest->tail->next;
dest->tail->data = x;
dest->tail->next = NULL;
}
}
int myStackPop(MyStack* obj) {
Queue* dest, *src;
int ret;
//让dest指向空队列 src指向有数据的队列
if (obj->q1.head == NULL)
{
dest = &obj->q1;
src = &obj->q2;
}
else
{
dest = &obj->q2;
src = &obj->q1;
}
ret = src->tail->data;
//将src指向的队列中队尾之前的数据依次出队放入dest指向的队列
while (src->head != src->tail)
{
QueueNode* next = src->head->next;
if (dest->head == NULL)//dest指向的队列为空(第一次放数据)
{
dest->head = dest->tail = malloc(sizeof (QueueNode));
dest->tail->data = src->head->data;
dest->tail->next = NULL;
}
else
{
dest->tail->next = malloc(sizeof (QueueNode));
dest->tail = dest->tail->next;
dest->tail->data = src->head->data;
dest->tail->next = NULL;
}
free(src->head);
src->head = next;
}
free(src->head);//最后一个数据释放 即进行了一次出栈操作
src->head = src->tail = NULL;//src指向的队列已清空
return ret;
}
四、实现Top接口
获取栈顶数据实际上是获取不为空的队列中队尾的数据,队列也支持直接访问队尾数据,因此只需要拿到不为空的队列就行了。
int myStackTop(MyStack* obj) {
Queue* src;
if (obj->q1.head)//拿到不为空的队列
src = &obj->q1;
else
src = &obj->q2;
return src->tail->data;
}
五、实现Empty接口
判断栈是否为空,实际上是判断两个队列是否为空,若两个队列都没有数据,则栈为空。
bool myStackEmpty(MyStack* obj) {
if (obj->q1.head || obj->q2.head)//只要其中一个队列有数据就返回false
return false;
return true;
}
六、栈的销毁
对栈进行销毁实际上是对不为空的队列中的所有数据进行出队操作,即释放掉该队列维护的所有节点并将队头队尾指针置空。
Queue* src;
//获取不为空的队列
if (obj->q1.head)
src = &obj->q1;
else
src = &obj->q2;
//若两个队列都为空也是可以的
while (src->head)
{
QueueNode* next = src->head->next;
free(src->head);
src->head = next;
}
src->tail = NULL;
free(obj);//注意这里要释放栈的空间