Leetcode 232. 用栈实现队列
typedef int TypeData;
struct Stack
{
TypeData* elem; //数组
int capacity; //数组的容量
int tail; //栈顶
};
typedef struct Stack Stack;
bool IsEmpty(Stack* ps)
{
assert(ps);
return ps->tail == 0;
}
TypeData pop(Stack* ps) //出栈
{
assert(ps);
assert(!IsEmpty(ps));
return ps->elem[--(ps->tail)];
}
TypeData peek(Stack* ps) //数据
{
assert(ps);
assert(!IsEmpty(ps));
return ps->elem[ps->tail - 1];
}
void InitStack(Stack* ps)
{
assert(ps);
ps->elem = NULL;
ps->capacity = 0;
ps->tail = 0;
}
void DestroyStack(Stack* ps)
{
assert(ps);
//free(ps->elem);
ps->elem = NULL;
ps->capacity = 0;
ps->tail = 0;
}
bool isFull(Stack* ps)
{
assert(ps);
return ps->capacity == ps->tail;
}
void push(Stack* ps, TypeData val)
{
assert(ps);
if (isFull(ps))
{
TypeData* newElem = (TypeData*)realloc(ps->elem, (ps->capacity + 3)*sizeof(TypeData));
assert(newElem);
ps->elem = newElem;
ps->capacity += 3;
}
ps->elem[ps->tail++] = val;
}
typedef struct {
Stack s1;//这个进
Stack s2;//这个出
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* myQueue = (MyQueue*)malloc(sizeof(MyQueue));
InitStack(&myQueue->s1);
InitStack(&myQueue->s2);
return myQueue;
}
bool myQueueEmpty(MyQueue* obj) {
return IsEmpty(&obj->s1);
}
void myQueuePush(MyQueue* obj, int x) {
assert(obj);
push(&obj->s1,x);
}
int myQueuePop(MyQueue* obj) {
if(myQueueEmpty(obj))
{
return -1;
}
int ret = -1;
while(!IsEmpty(&obj->s1))
{
ret = pop(&obj->s1);
if(!IsEmpty(&obj->s1))
{
push(&obj->s2,ret);
}
}
int x = 0;
while(!IsEmpty(&obj->s2))
{
push(&obj->s1, pop(&obj->s2));
}
return ret;
}
int myQueuePeek(MyQueue* obj) {
if(myQueueEmpty(obj))
{
return -1;
}
int ret = -1;
while(!IsEmpty(&obj->s1))
{
ret = pop(&obj->s1);
push(&obj->s2,ret);
}
int x = 0;
while(!IsEmpty(&obj->s2))
{
push(&obj->s1, pop(&obj->s2));
}
return ret;
}
void myQueueFree(MyQueue* obj) {
DestroyStack(&obj->s1);
DestroyStack(&obj->s2);
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);
*/