用两个栈实现队列
//栈的代码---------------------------首
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);
//判空
bool StackEmpty(ST* ps);
int StackSise(ST* ps);
//寻找顶点
STDatatype StackTop(ST* ps);
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;//-1
ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
if (ps->a)
{
free(ps->a);
}
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
//顶进顶出
//插入
void StackPush(ST* ps, STDatatype x)
{
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//不等于0改成2倍
STDatatype* tmp = realloc(ps->a, sizeof(STDatatype)*newcapacity);
if (tmp == NULL)
{
printf("realloc fail");
}
ps->a = tmp;
ps->capacity = newcapacity;
}
//初始值为0,先赋值再++
ps->a[ps->top] = x;
ps->top++;
}
//删除
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
--ps->top;
}
//判空
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSise(ST* ps)
{
assert(ps);
//因为初始化为0不是-1所以size就是top,-1要返回top+1
return ps->top;
}
//寻找顶点
STDatatype StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
//栈的代码----------------------------------尾
typedef struct {
ST pushST;//最好理解这里为什么不用指针
ST popST;
} MyQueue;
/** Initialize your data structure here. */
//创建空间并初始化
MyQueue* myQueueCreate() {
MyQueue* q=(MyQueue*)malloc(sizeof(MyQueue));
StackInit(&q->pushST);
StackInit(&q->popST);
return q;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
assert(obj);
StackPush(&obj->pushST,x);
}
/** Get the front element. */
//取队头的数据
int myQueuePeek(MyQueue* obj) {
assert(obj);
if(StackEmpty(&obj->popST))//如果第二个栈为空
{
while(!StackEmpty(&obj->pushST))//第一个栈不为空
{
//取数据插数据
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
return StackTop(&obj->popST);
}
/** Removes the element from in front of queue and returns that element. */
//注意看上方有返回值要求 ,int myQueuePop(MyQueue* obj)也可以看得出有返回值
int myQueuePop(MyQueue* obj) {
assert(obj);
if(StackEmpty(&obj->popST))//如果第二个栈为空
{
while(!StackEmpty(&obj->pushST))//第一个栈不为空
{
//取数据插数据
StackPush(&obj->popST,StackTop(&obj->pushST));
StackPop(&obj->pushST);
}
}
int front=StackTop(&obj->popST);//记录头
StackPop(&obj->popST);//队列-头出
return front;
//或者写
//int front=StackPop(&popST);
// StackPop(&obj->popST)
// return front;
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
assert(obj);
return StackEmpty(&obj->popST) && StackEmpty(&obj->pushST);//两者都为才为空
}
void myQueueFree(MyQueue* obj) {//销毁
StackDestroy(&obj->popST);
StackDestroy(&obj->pushST);
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* MyQueue* obj = myQueueCreate();
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/