leetcode-232. 用栈实现队列-C语言


#define LEN 0xfffff

typedef struct {
    int *stack1;
    int stack_index1;
    int *stack2;
    int stack_index2;
} MyQueue;

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
    MyQueue* obj = (MyQueue* )malloc(sizeof(MyQueue));
    obj->stack1 = (int *)malloc(sizeof(int) * LEN);
    obj->stack2 = (int *)malloc(sizeof(int) * LEN);
    obj->stack_index1 = 0;
    obj->stack_index2 = 0;
    
    return obj;
}

/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
    obj->stack1[obj->stack_index1++] = x;
}

/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
    int ret;
    
    if(!obj->stack_index2) {
        while(obj->stack_index1){
            obj->stack2[obj->stack_index2++] = obj->stack1[--obj->stack_index1];
        }
    }
    
    ret = obj->stack2[--obj->stack_index2];
    return ret;
}

/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
    if(!obj->stack_index2) {
        while(obj->stack_index1){
            obj->stack2[obj->stack_index2++] = obj->stack1[--obj->stack_index1];
        }
    }
    
    return obj->stack2[obj->stack_index2-1];  
}

/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
    if(!obj->stack_index1 && !obj->stack_index2) return true;
    return false;
}

void myQueueFree(MyQueue* 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);
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值