【C语言】用栈实现队列

用两个栈(后进先出)实现队列(先进先出)

题目:232. 用栈实现队列 - 力扣(LeetCode)

typedef int STDataType;
typedef struct Stack
{
    STDataType* _a;//数组
    int _top; // 栈顶,类似顺序表中的_size
    int _capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps)
{
    assert(ps);
    ps->_a = NULL;
    ps->_capacity = 0;
    ps->_top = 0;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(Stack* ps)
{
    assert(ps);
    return ps->_top == 0;
}
// 入栈
void StackPush(Stack* ps, STDataType data)
{
    assert(ps);
    //扩容
    if (ps->_capacity == ps->_top)
    {
        int newcapacity = ps->_capacity == 0 ? 4 : 2 * (ps->_capacity);
        STDataType* tmp = (STDataType*)realloc(ps->_a, newcapacity * sizeof(STDataType));
        if (tmp == NULL)
        {
            perror("realloc fail");
            return;
        }
        ps->_a = tmp;
        ps->_capacity = newcapacity;
    }
    ps->_a[ps->_top++] = data;
}
// 出栈
void StackPop(Stack* ps)
{
    assert(ps);
    assert(!StackEmpty(ps));
    
    ps->_top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
    assert(ps);
    return ps->_a[ps->_top-1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
    assert(ps);
    return ps->_top;
}

// 销毁栈
void StackDestroy(Stack* ps)
{
    assert(ps);
    ps->_capacity = ps->_top = 0;
    free(ps->_a);
    ps->_a = NULL;
}

typedef struct {
    Stack Spush;
    Stack Spop;
} MyQueue;

MyQueue* myQueueCreate() {
    MyQueue*p=(MyQueue*)malloc(sizeof(MyQueue));
    StackInit(&p->Spush);
    StackInit(&p->Spop);
    return p;
}

void myQueuePush(MyQueue* obj, int x) {
    StackPush(&obj->Spush,x);
}
int myQueuePeek(MyQueue* obj) {
    if(StackEmpty(&obj->Spop))
    {
        while(!StackEmpty(&obj->Spush))
        {
            int top=StackTop(&obj->Spush);
            StackPush(&obj->Spop,top);
            StackPop(&obj->Spush);
        }
    }
    return StackTop(&obj->Spop);
}

int myQueuePop(MyQueue* obj) {
    int front=myQueuePeek(obj);
    StackPop(&obj->Spop);
    return front;
}



bool myQueueEmpty(MyQueue* obj) {
    return StackEmpty(&obj->Spop)&&StackEmpty(&obj->Spush);
}

void myQueueFree(MyQueue* obj) {
    StackDestroy(&obj->Spop);
    StackDestroy(&obj->Spush);
    free(obj);
}

/**
 * Your MyQueue struct will be instantiated and called as such:
 * MyQueue* obj = myQueueCreate();
 * myQueuePush(obj, x);
 
 * int param_2 = myQueuePop(obj);
 
 * int param_3 = myQueuePeek(obj);
 
 * bool param_4 = myQueueEmpty(obj);
 
 * myQueueFree(obj);
*/

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值