方法1,创建两个stack喽。插入时将数据放入stack1。删除时,如果stack2为空,则将stack1的所有值放入stack2,然后再删除stack2的栈顶元素。如果两个stack都为空,则返回-1。
typedef struct {
int *s1;
int *s2;
int ss1,ss2;
} CQueue;
CQueue* cQueueCreate() {
CQueue * cq = (CQueue*)malloc(sizeof(CQueue));
cq->s1 = (int*)malloc(10000*sizeof(int));
cq->s2 = (int*)malloc(10000*sizeof(int));
cq->ss1 = 0;
cq->ss2 = 0;
return cq;
}
void cQueueAppendTail(CQueue* obj, int value) {
obj->s1[obj->ss1] = value;
obj->ss1++;
}
int cQueueDeleteHead(CQueue* obj) {
if (obj->ss2 == 0) {
if (obj->ss1 == 0) return -1;
int j = obj->ss2;
for (int i = obj->ss1-1;i >= 0;i--) {
obj->s2[j] = obj->s1[i];
j++;
}
obj->ss2 = j;
obj->ss1 = 0;
}
obj->ss2--;
return obj->s2[obj->ss2];
}
void cQueueFree(CQueue* obj) {
free(obj->s1);
free(obj->s2);
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);
*/
leedcode通过,输出结果为:
执行用时:364 ms, 在所有 C 提交中击败了54.32% 的用户
内存消耗:80.5 MB, 在所有 C 提交中击败了40.97% 的用户