1.思路分析
栈 先进后出
队列 先进先出
我们创建两个栈
栈一 存放1 2 3 4,出栈为1,可是我们队列出队结果为4,我们可以先将这个栈的数据导入到栈二
这时我们出栈二,发现出来的是1
从上可知我们只需要将栈一数据导入栈二导出即可
2.代码实现
#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDatatype;
typedef struct stack
{
STDatatype* a;
int top;
int capacity;
}ST;
void StackInit(ST* ps);
void StackDestroy(ST* ps);
void StackPush(ST* ps, STDatatype x);
void StackPop(ST* ps);
STDatatype StackTop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
void StackInit(ST* ps)
{
assert(ps);
ps->a = (STDatatype*)malloc(sizeof(STDatatype) * 4);
if (ps->a == NULL)
{
perror("malloc fail");
exit(-1);
}
ps->top = 0;
ps->capacity = 4;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->top = 0;
ps->capacity = 0;
}
void StackPush(ST* ps, STDatatype x)
{
assert(ps);
if (ps->top == ps->capacity)
{
STDatatype* tmp = (STDatatype*)realloc(ps->a, ps->capacity * 2 * sizeof(STDatatype));
if (tmp == NULL)
{
perror("malloc");
exit(-1);
}
ps->capacity *= 2;
ps->a = tmp;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
/*assert(ps->top > 0);*/
assert(!StackEmpty(ps));
ps->top--;
}
STDatatype StackTop(ST* ps)
{
assert(ps);
//assert(ps->top > 0);
assert(!StackEmpty(ps));
return ps->a[ps->top-1];
}
bool StackEmpty(ST* ps)
{
assert(ps);
return(ps->top == 0);
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
//正文开始
typedef struct {
ST pushst;
ST popst;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue*pq=(MyQueue*)malloc(sizeof(MyQueue));
StackInit(&pq->pushst);//初始化两个站
StackInit(&pq->popst);
return pq;
}
void myQueuePush(MyQueue* obj, int x) {
assert(obj);
StackPush(&obj->pushst,x);
}
int myQueuePeek(MyQueue* obj);
bool myQueueEmpty(MyQueue* obj);
int myQueuePop(MyQueue* obj) {
assert(obj);
assert(!myQueueEmpty(obj));
int peek=myQueuePeek(obj);
StackPop(&obj->popst);
return peek;
}
int myQueuePeek(MyQueue* obj) {
assert(obj);
assert(!myQueueEmpty(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) {
assert(obj);
return (StackEmpty(&obj->pushst)&&StackEmpty(&obj->popst));
}
void myQueueFree(MyQueue* obj) {
assert(obj);
StackDestroy(&obj->pushst);
StackDestroy(&obj->popst);
free(obj);
}