剑指面试题09. 用两个栈实现队列 (STL和C两种实现)

解法1:借助STL的stack

class CQueue {
private:
    stack<int> stack_in;        //入栈
    stack<int> stack_out;       //出栈
public:
    CQueue() {

    }
    
    void appendTail(int value) {
        stack_in.push(value);
    }
    
    int deleteHead() {
        int res = -1;
        if (!stack_out.empty()) {
            res = stack_out.top();
            stack_out.pop();
            return res;
        }

        if (stack_in.empty())
            return -1;

        while (!stack_in.empty()) {  //将入栈的值全部push到出栈里
            res = stack_in.top();
            stack_in.pop();
            stack_out.push(res);
        }
        res = stack_out.top();
        stack_out.pop();

        return res;
    }
};

解法2:C语言实现

注:思路基本上和STL实现的一致。因为stack底层已经封装好了初始化和方法,所以整体看起来STL实现的比C语言要简练,但是C语言实现中,小细节考的很全面。

#define STACK_IN_LEN  10000
#define STACK_OUT_LEN 10000

typedef struct { //列队的成员是两个栈
    int top_in;
    int *stack_in;

    int top_out;
    int *stack_out;
} CQueue;

CQueue* cQueueCreate() {
    CQueue* obj = (CQueue*)calloc(1, sizeof(CQueue));

    obj->top_in = -1;    //说明栈空
    obj->stack_in = (int*)calloc(STACK_IN_LEN, sizeof(int));
    obj->top_out = -1;
    obj->stack_out = (int*)calloc(STACK_OUT_LEN, sizeof(int));

    return obj;
}

void cQueueAppendTail(CQueue* obj, int value) {
    obj->stack_in[++obj->top_in] = value;    //top_in先执行++操作,因为初值是-1
}

int cQueueDeleteHead(CQueue* obj) {
    int res = -1;
    if (obj->top_out != -1) {
        res = obj->stack_out[obj->top_out];
        obj->top_out--;
        return res;
    }

    if (obj->top_in == -1)
        return -1;
    
    while (obj->top_in != -1)      //top_out先++,top_in后--
        obj->stack_out[++obj->top_out] = obj->stack_in[obj->top_in--];
    res = obj->stack_out[obj->top_out];
    obj->top_out--;

    return res;
}

void cQueueFree(CQueue* obj) {
    free(obj->stack_in);
    free(obj->stack_out);
    free(obj);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值