剑指Offer 09.用两个栈实现队列(c语言)

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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 \leqslant values \leqslant 10000\
最多会对 appendTail、deleteHead 进行 10000 次调用
$$
代码如下:

/*
入队操作:push元素到s1;
出队操作:s2非空时,直接从s2弹出元素;s2为空时,把s1中的元素逐个弹出压入s2,再从s2中弹出。
*/
#define MAXSIZE 10000 

typedef struct{
    int *data;
    int top;
} Stack;

bool emptyStack(Stack *s)
{
    return s->top == 0;
}

/*push element*/
void pushStack(Stack *s, int x)
{
    if(s->top == MAXSIZE){
        return;
    }
    s->data[s->top++] = x;
}

/*pop element*/
int popStack(Stack *s)
{
    if(emptyStack(s)){
        return -1;
    }
    return s->data[--s->top];
}

typedef struct {
    Stack *s1;
    Stack *s2;
} CQueue;


CQueue* cQueueCreate() {
    CQueue *obj = (CQueue*)malloc(sizeof(CQueue));
    obj->s1 = (Stack*)malloc(sizeof(Stack));
    obj->s1->data = (int*)malloc(sizeof(int)*MAXSIZE);
    obj->s1->top = 0;
    obj->s2 = (Stack*)malloc(sizeof(Stack));
    obj->s2->data = (int*)malloc(sizeof(int)*MAXSIZE);
    obj->s2->top = 0;
    return obj;
}

/*
功能:往队列中插入元素;
只往s1中push。
传入参数:obj,队列对象;value,待插入元素;
*/
void cQueueAppendTail(CQueue* obj, int value) {
    pushStack(obj->s1, value);
}

/*
功能:从队列中删除元素;
s2非空时,直接从s2弹出元素;s2为空时,把s1中的元素逐个弹出压入s2,再从s2中弹出。
传入参数:obj,队列对象;
*/
int cQueueDeleteHead(CQueue* obj) {
    if(emptyStack(obj->s1) && emptyStack(obj->s2)){
        return -1;
    }
    int x;
    if(emptyStack(obj->s2)) {
        while(!emptyStack(obj->s1))
        {
            x = popStack(obj->s1);
            pushStack(obj->s2, x);
        }
    }
    return popStack(obj->s2);
}

void cQueueFree(CQueue* obj) {
    free(obj->s1->data);
    free(obj->s2->data);
    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);
*/
posted @ 2023-04-22 13:42  调蓝师  阅读(20)  评论(0)    收藏  举报