232. 用栈实现队列
思路:两个栈实现一个队列,在 push 时,直接入栈就好了;pop 时,若输出栈为空,酒吧进栈数据全部导进来,再弹出;如果出栈不为空,直接出栈就好了;peek 与 pop一样,但只读数据,不出栈;当入栈和出栈都空,返回 true
typedef struct{
int *stk;
int size;
}Stack;
Stack *stkCreate(int capcity){
Stack *create = malloc(sizeof(Stack));
create->stk = malloc(sizeof(int)*capcity);
create->size = 0;
return create;
}
void stkPush(Stack *s,int x){
s->stk[s->size++]=x;
}
void stkPop(Stack *s){
s->size--;
}
int stkPeek(Stack *s){
return s->stk[s->size-1];
}
bool stkIsEmpty(Stack *s){
return s->size == 0;
}
void stkFree(Stack *s){
free(s->stk);
}
typedef struct {
Stack *stkOut;
Stack *stkIn;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue *create = malloc(sizeof(MyQueue));
create->stkIn = stkCreate(100);
create->stkOut = stkCreate(100);
return create;
}
void myQueuePush(MyQueue* obj, int x) {
stkPush(obj->stkIn,x);
}
int myQueuePop(MyQueue* obj) {
if(stkIsEmpty(obj->stkOut)){
while(!stkIsEmpty(obj->stkIn)){
stkPush(obj->stkOut,stkPeek(obj->stkIn));
stkPop(obj->stkIn);
}
}
int result = stkPeek(obj->stkOut);
stkPop(obj->stkOut);
return result;
}
int myQueuePeek(MyQueue* obj) {
if(stkIsEmpty(obj->stkOut)){
while(!stkIsEmpty(obj->stkIn)){
stkPush(obj->stkOut,stkPeek(obj->stkIn));
stkPop(obj->stkIn);
}
}
return stkPeek(obj->stkOut);
}
bool myQueueEmpty(MyQueue* obj) {
return stkIsEmpty(obj->stkIn)&&stkIsEmpty(obj->stkOut);
}
void myQueueFree(MyQueue* obj) {
stkFree(obj->stkIn);
stkFree(obj->stkOut);
}
/**
* 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);
*/
225. 用队列实现栈
思路:用一个队列就可以实现;
出栈时:将队列里队尾最后一个元素前的所有元素全部重新进人队列,并弹出队列;
当 rear == head 栈空
typedef struct {
int queue[1000];
int head;
int rear;
} MyStack;
MyStack* myStackCreate() {
MyStack *stack = malloc(sizeof(MyStack));
stack->rear = 0;
stack->head = 0;
return stack;
}
void myStackPush(MyStack* obj, int x) {
obj->queue[obj->rear++] = x;
}
int myStackPop(MyStack* obj) {
int size = (obj->rear) - (obj->head);
while(size-->1){
obj->queue[obj->rear++] = obj->queue[obj->head++];
}
int result = obj->queue[obj->head++];
return result;
}
int myStackTop(MyStack *obj){
return obj->queue[obj->rear-1];
}
bool myStackEmpty(MyStack* obj) {
if(obj->head == obj->rear)
return true;
return false;
}
void myStackFree(MyStack* obj) {
free(obj);
}
/**
* Your MyStack struct will be instantiated and called as such:
* MyStack* obj = myStackCreate();
* myStackPush(obj, x);
* int param_2 = myStackPop(obj);
* int param_3 = myStackTop(obj);
* bool param_4 = myStackEmpty(obj);
* myStackFree(obj);
*/