用两个栈实现队列

目录

一、栈的基本结构及其接口

二、我的队列结构定义

三、我的队列创建及其初始化

四、我的队列入队

五、我的队列出队

六、我的队列取队头元素

七、我的队列判空

八、我的队列销毁


一、栈的基本结构及其接口


//栈的结构定义
typedef int STDataType;
 
typedef struct Stack{
    STDataType *a;
    int top;
    int capacity;
}ST;
 
//栈的初始化
void STInit(ST* pst)
{
    pst->a=NULL;
    pst->top=0;
    pst->capacity=0;
}
 
//栈的扩容
void checkcapacity(ST* pst)
{
    if(pst->top==pst->capacity)
    {
        int newcapacity=pst->capacity==0?4:pst->capacity*4;
        STDataType* tmp=(STDataType*)realloc(pst->a,sizeof(STDataType)*newcapacity);
        if(tmp==NULL)
    
        {
            perror("realloc fail");
            exit(-1);
        }
        pst->a=tmp;
        pst->capacity=newcapacity;
    }
}
 
//入栈
void STPush(ST* pst,STDataType x)
{
    assert(pst);
    checkcapacity(pst);
    pst->a[pst->top++]=x;
}
 
//出栈
void STPop(ST* pst)
{
    assert(pst);
    
    assert(pst->top);//空栈
    pst->top--;
}
 
//取栈顶元素
STDataType STTop(ST* pst)
{
    assert(pst);
    assert(pst->top);//空栈
    return pst->a[pst->top-1];
}
 
//判断栈是否为空
bool STEmpty(ST* pst)
{
    return pst->top==0;
}
 
//销毁栈
void STDestroy(ST* pst)
{
    assert(pst);
    free(pst->a);
    pst->a=NULL;
    pst->top=0;
    pst->capacity=0;
 
}

二、我的队列结构定义

//我的队列
typedef struct {
    ST s1;
    ST s2;
} MyQueue;

三、我的队列创建及其初始化

//我的队列的创建及其初始化
MyQueue* myQueueCreate() {
    MyQueue* myqueue=(MyQueue*)malloc(sizeof(MyQueue));
    if(myqueue==NULL)
    {
    
        perror("malloc fail");
        exit(-1);
    }
    STInit(&myqueue->s1);
    STInit(&myqueue->s2);
    return myqueue;
}

四、我的队列入队

//我的队列入队
void myQueuePush(MyQueue* obj, int x) {
    STPush(&obj->s1,x);
}

五、我的队列出队

//我的队列出队
int myQueuePop(MyQueue* obj) {
    while(obj->s1.top>1)
    {
        STPush(&obj->s2,STTop(&obj->s1));
        STPop(&obj->s1);
    }
    int tmp=STTop(&obj->s1);
    STPop(&obj->s1);
    
    while(obj->s2.top>0)
    {
        STPush(&obj->s1,STTop(&obj->s2));
        STPop(&obj->s2);
    }
    return tmp;
}

六、我的队列取队头元素

//我的队列取队头元素
int myQueuePeek(MyQueue* obj) {
    while(obj->s1.top>1)
    {
        STPush(&obj->s2,STTop(&obj->s1));
        STPop(&obj->s1);
    }
    int tmp=STTop(&obj->s1);
    while(obj->s2.top>0)
    {
        STPush(&obj->s1,STTop(&obj->s2));
        STPop(&obj->s2);
    }
    return tmp;
}

七、我的队列判空

//我的队列判空
bool myQueueEmpty(MyQueue* obj) {
    return STEmpty(&obj->s1);
}

八、我的队列销毁

//我的队列销毁
void myQueueFree(MyQueue* obj) {
    STDestroy(&obj->s1);
    STDestroy(&obj->s2);
    free(obj);
    obj=NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南林yan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值