解法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);
}