我已经为Stack ADT实现了几个功能。我试图在 O(1) 时间内找到最大值和最小值,并且我增强了堆栈结构来实现此目的。这是我的代码:
void mms_push(MMStack mms, int i) {
struct llnode *new = malloc(sizeof(struct llnode));
new->item = i;
if(mms->len!=0)
{
new->next = mms->topnode;
mms->topnode = new;
}
else
{
new->next = NULL;
mms->topnode = new;
}
if (mms->len == 0)
{
mms->topnode->minc = i;
mms->topnode->maxc = i;}
else
{
if(mms->topnode->maxc < i)
{
mms->topnode->maxc = i;
}
if(i<mms->topnode->minc)
{
mms->topnode->minc = i;
}
mms->len++;}
int mms_pop(MMStack mms) {
assert(mms);
int ret = mms->topnode->item;
struct llnode *backup = mms->topnode;
mms->topnode = mms->topnode->next;
mms->len--;
free(backup);
return ret;
}
我使用的结构如下:
struct llnode
{
int item;
struct llnode *next;
int minc;
int maxc;
};
struct mmstack
{
int len ;
struct llnode *topnode;
};
typedef struct mmstack *MMStack;
我没有得到正确的最大值和最小值。如何更正代码以便获得堆栈中最大和最小元素的正确值?
提前致谢!
最佳答案
看一下这段代码:
if (mms->len == 0)
{
mms->topnode->minc = i;
mms->topnode->maxc = i;
}
else
{
if(mms->topnode->maxc < i)
{
mms->topnode->maxc = i;
}
if(i<mms->topnode->minc)
{
mms->topnode->minc = i;
}
}
请注意,在 else
分支中,您正在读取 mms->topnode->minc
和 mms->topnode->maxc< 的值
在初始化它们之前。我认为您打算在重新分配 mms->topnode->minc
/maxc
之前查看 mms->topnode->minc
的值。要解决此问题,请尝试执行以下操作:
else
{
mms->topnode->maxc = mms->topnode->next->maxc;
mms->topnode->minc = mms->topnode->next->minc;
if(mms->topnode->maxc < i)
{
mms->topnode->maxc = i;
}
if(i<mms->topnode->minc)
{
mms->topnode->minc = i;
}
}
这些额外的两行在与 i
进行比较之前将最小值和最大值初始化为旧的最大值,这应该确保它们获得一个值。
希望这有帮助!
关于c - 使用 O(1) find-max/find-min 实现堆栈时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29379131/