栈和队列的实现方式参考博客:https://blog.csdn.net/cx2479750196/article/details/80493848
1、两个栈实现一个队列
typedef struct QueuewithStack{
SeqStack entry;
SeqStack exit;
}QueuewithStack;
typedef char QueueType;
****************************************************************************************************************************
void QueuewithStackInit(QueuewithStack* q){
if (q == NULL){
return;
}
SeqStackInit(&q->entry);
SeqStackInit(&q->exit);
}
void QueuewithStackPush(QueuewithStack* q,QueueType value){
if (q == NULL){
return;
}
QueueType tmp;//查看exit中是否有元素,循环取栈顶元素插入entry中
while (SeqStackFindTop(&q->exit, &tmp)){
SeqStackPop(&q->exit);
SeqStackPush(&q->entry, tmp);
}
//此时exit为空
SeqStackPush(&q->entry, value);
}
void QueuewithStackPop(QueuewithStack* q){
if (q == NULL){
return;
}
QueueType tmp;//出队列时要将数据放在exit中然后不断pop
while (SeqStackFindTop(&q->entry, &tmp)){
SeqStackPop(&q->entry);
SeqStackPush(&q->exit, tmp);
}
SeqStackPop(&q->exit);
}
int QueuewithStack_FindTop(QueuewithStack* q, QueueType* value){
if (q == NULL||value==NULL){
return 0;
}
QueueType tmp;//将entry中的元素倒腾到exit中,然后才能准确的取出队首元素
while (SeqStackFindTop(&q->entry, &tmp)){
SeqStackPop(&q->entry);
SeqStackPush(&q->exit, tmp);
}
int ret=SeqStackFindTop(&q->exit,value);
return ret;
}
2、两个队列实现一个栈
typedef struct StackwithQueue{
SeqQueue q1;
SeqQueue q2;
}StackwithQueue;
typedef char StackwithQueueType;
void Init(StackwithQueue* Sq){
if (Sq == NULL){
return;
}
QueueInit(&Sq->q1);
QueueInit(&Sq->q2);
}
void Push(StackwithQueue* Sq, StackwithQueueType data){
if (Sq == NULL){
return;
}
//无论如何不可能两个队同时为空,也不可能两个