文章目录
- ==**栈接口见 [算法开启小码农栈血脉](https://blog.csdn.net/diandengren/article/details/121055584?spm=1001.2014.3001.5501)**==
- 用栈实现队列
- 题目
- 队结构体
- 队初始化
- 入“队”
- 出“队”并取出队元素
- 返回队头
- 判断队空
- 队列销毁
- 队列代码(接口代码去我之前文章取) [算法开启小码农栈血脉](https://blog.csdn.net/diandengren/article/details/121055584?spm=1001.2014.3001.5501)
题目
![image-20211102223625269](https://img-blog.csdnimg.cn/img_convert/ad7f89444fc76b044ff9490dca184cbc.png)
队结构体
typedef struct {
ST PushST;
ST PopST;
} MyQueue;
队初始化
MyQueue* myQueueCreate() {
MyQueue* q = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&q->PushST);
StackInit(&q->PopST);
return q;
}
入“队”
![](https://img-blog.csdnimg.cn/img_convert/e56f0ed675763cab310cec0a38ab5298.gif)
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->PushST,x);
}
出“队”并取出队元素
![](https://img-blog.csdnimg.cn/img_convert/ed36c712a1ae9a03ff1287804713726f.gif)
int myQueuePop(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{
while(!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST,StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
int tmp = StackTop(&obj->PopST);
StackPop(&obj->PopST);
return tmp;
}
返回队头
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{
while(!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST,StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
return StackTop(&obj->PopST);
}
判断队空
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->PushST) && StackEmpty(&obj->PopST);
}
队列销毁
void myQueueFree(MyQueue* obj) {
StackDestroy(&obj->PushST);
StackDestroy(&obj->PopST);
free(obj);
}
![image-20211103001539223](https://img-blog.csdnimg.cn/img_convert/5ae3f5c510e1862a4880103582f84cc7.png)
typedef struct {
ST PushST;
ST PopST;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* q = (MyQueue*)malloc(sizeof(MyQueue));
StackInit(&q->PushST);
StackInit(&q->PopST);
return q;
}
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->PushST,x);
}
int myQueuePop(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{
while(!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST,StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
int tmp = StackTop(&obj->PopST);
StackPop(&obj->PopST);
return tmp;
}
int myQueuePeek(MyQueue* obj) {
if(StackEmpty(&obj->PopST))
{
while(!StackEmpty(&obj->PushST))
{
StackPush(&obj->PopST,StackTop(&obj->PushST));
StackPop(&obj->PushST);
}
}
return StackTop(&obj->PopST);
}
bool myQueueEmpty(MyQueue* obj) {
return StackEmpty(&obj->PushST) && StackEmpty(&obj->PopST);
}
void myQueueFree(MyQueue* obj) {
StackDestroy(&obj->PushST);
StackDestroy(&obj->PopST);
free(obj);
}