求 leetcode Min Stack 的 C 语言解

2015-05-05 23:15:11 +08:00
 fszaer

原题链接
https://leetcode.com/problems/min-stack/
题意简单而言就是要实现一个快速求min的stack
这题本身不难,其实我用js已经AC了
但是当我用C重写一遍后一直re,我翻了leetcode的论坛没有发现我这个错误相关的问题在哪,也没有发现一个可行的C语言版题解,所以来这里问问
这里是我的reC语言解

typedef struct {
    int *number;
    int *min;
    int ntop;
    int mtop;
} MinStack;

void minStackCreate(MinStack *stack, int maxSize) {
    stack->number = (int*)malloc(maxSize*sizeof(int));
    stack->min = (int*)malloc(maxSize*sizeof(int));
    stack->mtop = stack->ntop = 0;
    stack->maxSize = maxSize;
}

void minStackPush(MinStack *stack, int element) {
    stack->number[stack->ntop++] = element;
    if (stack->mtop != 0) {
        if (element <= stack->min[stack->mtop - 1])
            stack->min[stack->mtop++] = element;
    }
    else
        stack->min[stack->mtop++] = element;
}

void minStackPop(MinStack *stack) {
    int temp = stack->number[stack->ntop--];
    if (temp == stack->min[stack->mtop - 1])
        stack->mtop--;
}

int minStackTop(MinStack *stack) {
    return stack->number[stack->ntop - 1];
}

int minStackGetMin(MinStack *stack) {
    return stack->min[stack->mtop - 1];
}

void minStackDestroy(MinStack *stack) {
    free(stack->min);
    free(stack->number);
}
3577 次点击
所在节点    问与答
6 条回复
jiang42
2015-05-06 03:28:04 +08:00
把两个free去掉。。。
Andiry
2015-05-06 06:51:57 +08:00
因为槽点实在太多,所以自己写了一个

typedef struct {
int *number;
int *min;
int top;
int maxSize;
} MinStack;

void minStackCreate(MinStack *stack, int maxSize) {
stack->number = (int*)malloc(maxSize*sizeof(int));
stack->min = (int*)malloc(maxSize*sizeof(int));
stack->top = 0;
stack->maxSize = maxSize;
}

void minStackPush(MinStack *stack, int element) {
int top = stack->top;

if (top >= stack->maxSize - 1)
return;

stack->number[top] = element;
if (top == 0) {
stack->min[top] = element;
} else {
int min = stack->min[top - 1];
if (element < min)
stack->min[top] = element;
else
stack->min[top] = min;
}

stack->top++;
}

void minStackPop(MinStack *stack) {
if (stack->top == 0)
return;
stack->top--;
}

int minStackTop(MinStack *stack) {
if (stack->top == 0)
return 0;
return stack->number[stack->top - 1];
}

int minStackGetMin(MinStack *stack) {
if (stack->top == 0)
return 0;
return stack->min[stack->top - 1];
}

void minStackDestroy(MinStack *stack) {
free(stack->min);
free(stack->number);
}
Andiry
2015-05-06 06:52:48 +08:00
缩进全都没有了,随便看看吧
jky
2015-05-06 08:04:39 +08:00
void minStackPush(MinStack *stack, int element) {
if (stack->ntop == stack->maxSize) return;
...
}
fszaer
2015-05-06 09:11:31 +08:00
@Andiry
啊,谢谢指教,参考了你的代码
终于知道哪里出了问题,才发现自己对边际条件的检查还不够
billwsy
2015-06-11 14:56:44 +08:00
push和pop检查有没有超出maxSize或0, 另外pop中int temp = stack->number[--stack->ntop];

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/188752

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX