we will rise. 2023-10-30 16:37 采纳率: 100%
浏览 7
已结题

力扣用栈实现队列出现矛盾问题

一直编译不过去,分析问题后发现是5提前入了创建的第二个栈,但一直找不到原因,于是测试了一下,发现一个很矛盾的问题。
题目链接如下
https://leetcode.cn/problems/implement-queue-using-stacks/
测试结果如下

img

img


代码如下

typedef int STDataType;
typedef struct Stack
{
    STDataType* a;
    int top;
    int capacity;
}ST;

void STInit(ST* ps);
void STDestroy(ST* ps);
//入栈
void STPush(ST* ps,STDataType x);
//出栈
void STPop(ST* ps);

int STSize(ST* ps);

bool STEmpty(ST* ps);

//获取栈顶元素
STDataType STTop(ST* ps);

void STInit(ST* ps)
{
    assert(ps);
    ps->a = NULL;
    ps->capacity = 0;
    ps->top = 0;
}

void STDestroy(ST* ps)
{
    assert(ps);

    free(ps->a);
    ps->a = NULL;
    ps->top = ps->capacity = 0;
}

void STPush(ST* ps, STDataType x)
{
    assert(ps);
    // 11:40
    if (ps->top == ps->capacity)
    {
        int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newCapacity);
        if (tmp == NULL)
        {
            perror("realloc fail");
            exit(-1);
        }

        ps->a = tmp;
        ps->capacity = newCapacity;
    }

    ps->a[ps->top] = x;
    ps->top++;
}

void STPop(ST* ps)
{
    assert(ps);

    // 
    assert(ps->top > 0);

    --ps->top;
}

STDataType STTop(ST* ps)
{
    assert(ps);

    // 
    assert(ps->top > 0);

    return ps->a[ps->top - 1];
}

int STSize(ST* ps)
{
    assert(ps);

    return ps->top;
}

bool STEmpty(ST* ps)
{
    assert(ps);

    return ps->top == 0;
}

typedef struct {
    ST st1;
    ST st2;
} MyQueue;


MyQueue* myQueueCreate() {
    MyQueue* myque =(MyQueue*)malloc(sizeof(MyQueue));
    STInit(&myque->st1);
    STInit(&myque->st2);
    return myque;
}

void myQueuePush(MyQueue* obj, int x) {
    STPush(&obj->st1,x);
}


int myQueuePeek(MyQueue* obj) {
    if(STEmpty(&obj->st2)==true);
    {
        //导数据
        while(!STEmpty(&obj->st1))
        {
            STPush(&obj->st2,STTop(&obj->st1));
            STPop(&obj->st1);
        }

    }
    return STTop(&obj->st2);
}

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


bool myQueueEmpty(MyQueue* obj) {
    return STEmpty(&obj->st1)&&STEmpty(&obj->st2);
}

void myQueueFree(MyQueue* obj) {
    
    STDestroy(&obj->st1);
    STDestroy(&obj->st2);
    free(obj);
}
  • 写回答

2条回答 默认 最新

  • 无序繁星 2023-10-30 16:55
    关注

    判断语句后面有分号,后面的代码不管判断结果都会执行

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月7日
  • 已采纳回答 10月30日
  • 创建了问题 10月30日

悬赏问题

  • ¥15 关于#单片机#的问题:以ATMEGA128或相近型号单片机为控制器设计直流电机调速的闭环控制系统(相关搜索:设计报告|软件设计|流程图)
  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办