用栈实现队列
https://leetcode-cn.com/problems/implement-queue-using-stacks/
思路:通过两个栈来实现
//实现栈建议数组
typedef int STDdataType;
typedef struct Stack{
STDdataType *_a;
int _top;
int _capacity;
}Stack;
//初始化
void StackInit(Stack*pst){
assert(pst);
pst->_a=malloc(sizeof(STDdataType)*5);
pst->_top=0;
pst->_capacity=5;
}
//压栈
void StackPush(Stack*pst,STDdataType data){
assert(pst);
if(pst->_top==pst->_capacity){
pst->_capacity*=2;
pst->_a=(STDdataType*)realloc(pst->_a,sizeof(STDdataType)*pst->_capacity);
if(pst->_a==NULL){
printf("内存不足!");
exit(-1);
}
}
pst->_a[pst->_top]=data;
pst->_top++;
}
//弹出
void StackPop(Stack*pst){
assert(pst);
assert(pst->_top>0);
pst->_top-=1;
}
//获取栈顶
STDdataType StackTop(Stack*pst){
assert(pst);
assert(pst->_top>0);
return (pst->_a[pst->_top-1]);
}
//判空
int StackEmpty(Stack*pst){
assert(pst);
return pst->_top==0?1:0;
}
//销毁
void StackDestroy(Stack*pst){
assert(pst);
free(pst->_a);
pst->_a=NULL;
pst->_top=pst->_capacity=0;
}
//获取数据个数
int StackSize(Stack *pst){
assert(pst);
return pst->_top;
}
typedef struct {
Stack _pushST;
Stack _popST;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueue*q=(MyQueue*)malloc(sizeof(MyQueue));
StackInit(&q->_pushST);
StackInit(&q->_popST);
return q; // 对应于下面的obj
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
StackPush(&obj->_pushST,x);
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
int front=myQueuePeek(obj);
StackPop(&obj->_popST);
return front;
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
//注意获队头元素,如果pushST里的元素都入到popST里,但是popST只出了部分,当再次想popST里出元素的时候,还是要先出popST里的
//所以要先判断popST里有没有出干净
if(!StackEmpty(&obj->_popST)){
return StackTop(&obj->_popST);
}
else{
while(!StackEmpty(&obj->_pushST)){
StackPush(&obj->_popST,StackTop(&obj->_pushST));
StackPop(&obj->_pushST);
}
return StackTop(&obj->_popST);
}
}
/** Returns whether the queue is empty. */
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);
*/