剑指 Offer 09. 用两个栈实现队列
简单
题目:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
1.双栈,用数组作为栈;维护两个栈,第一个栈支持插入操作,第二个栈支持删除操作。根据栈先入后出的性质,我们往第一个栈里面插入元素,当要出栈或者删除元素时,我们先将栈A里的元素依次出栈再压入栈B中,这样就做到了队列的性质先入先出。
C代码:
typedef struct {
int *stackA;
int *stackB;
int topA;
int topB;
} CQueue;
CQueue* cQueueCreate() {
CQueue *cq;
cq = (CQueue*)malloc(sizeof(CQueue));
cq->stackA = (int*)malloc(sizeof(int) * 10001);
cq->topA = -1;
cq->stackB = (int*)malloc(sizeof(int) * 10001);
cq->topB = -1;
return cq;
}
void cQueueAppendTail(CQueue* obj, int value) {
obj->stackA[++obj->topA] = value;
}
int cQueueDeleteHead(CQueue* obj) {
if(obj->topB != -1) {
return obj->stackB[obj->topB--];
}
if(obj->topB == -1 && obj->topA != -1) {
while(obj->topA != -1) {
obj->stackB[++obj->topB] = obj->stackA[obj->topA--];
}
}
if(obj->topB != -1) {
return obj->stackB[obj->topB--];
}
return -1;
}
void cQueueFree(CQueue* obj) {
free(obj);
}
/**
* Your CQueue struct will be instantiated and called as such:
* CQueue* obj = cQueueCreate();
* cQueueAppendTail(obj, value);
* int param_2 = cQueueDeleteHead(obj);
* cQueueFree(obj);
*/