文章目录
- ==**栈接口见 [算法开启小码农栈血脉](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)
题目
队结构体
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);
}
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);
}