链接:力扣
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;//法1.初始化top=-1;则top先++,再放入元素到top处,此时放完最后一个元素后,top等于最后一个元素的下标,即栈顶的下标,此时的top+1才等于capacity;
//法2.初始化top=0;则先放元素到top处,再top++;此时放完最后一个元素,也就是放完栈顶的那个元素后,top等于栈顶(最后的那个元素)的下标+1,此时的top=capacity;此处采用法2
int capacity;
}ST;
STDataType StackTop(ST* ps)
{
return ps->a[ps->top-1];
}
ST* CheckCapactiy(ST* ps)
{
STDataType* tmp = NULL;
int NewCapacity = ps->capacity == 0 ? 4:2 * (ps->capacity);
tmp = (STDataType*)realloc(ps->a, NewCapacity);
if (tmp != NULL)
{
ps->a = tmp;//!!!注意是给ps->a开辟的空间,而不是给ps
ps->capacity = NewCapacity;
printf("扩容成功\n");
return ps;//!!!记得要把ps return 回去
}
else
{
printf("扩容失败\n");
perror("CheckCapacity::realloc");
exit(-1);
}
}
void StackPop(ST* ps)
{
if (ps->top <= 0)
{
printf("栈为空\n");
return;
}
else
{
ps->top--;
}
}
void StackPush(ST* ps, STDataType x)
{
ps=CheckCapactiy(ps);
ps->a[ps->top] = x;
ps->top++;
}
void StackDestroy(ST* ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
bool StackEmpty(ST* ps)//若为空则返回1;若不为空则返回负的随机值
{
return ps->top == 0;
}
int StackSize(ST* ps)
{
return ps->top - 1;
}
typedef struct {
ST pushst;
ST popst;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* obj=(MyQueue*)malloc(sizeof(MyQueue));
assert(obj);
StackInit(&obj->pushst);
StackInit(&obj->popst);
return obj;
}
void myQueuePush(MyQueue* obj, int x) {
//因为每次pop或者是取队头元素当popst为空的时候会将pushst里的元素全部倒到空的popst里,确保了每次放元素时候要么push里面的是空的,要么完好无动的顺序的!!!!整个逻辑实现的关键点
StackPush(&obj->pushst,x);
}
int myQueuePop(MyQueue* obj)//出完了才会去push里面拿,一拿就是全部拿//出队列,必须是队头的元素出,也就先放进去的,也就是pushst的栈底元素,也就是倒到popst的栈顶元素
{
if(StackEmpty(&obj->popst))//如果popst里为空,先将全部push中的倒过去
{
//先将pushst的元素全部倒到popst中
while(!StackEmpty(&obj->pushst))
{
StackPush(&obj->popst,StackTop(&obj->pushst));
StackPop(&obj->pushst);
}
}
//再将栈顶元素pop出去,并返回他
int front=StackTop(&obj->popst);
StackPop(&obj->popst);
return front;
}
int myQueuePeek(MyQueue* obj)//返回队头元素,即push中的栈底元素,也就是倒过去pop里面之后的栈顶元素
{
if(StackEmpty(&obj->popst))//如果popst里为空,先将全部push中的倒过去
{
//先将pushst的元素全部倒到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);
}
/**
* 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);
*/