c - 使用 O(1) find-max/find-min 实现堆栈时出错?

标签 c data-structures stack

我已经为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->mincmms->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/

相关文章:

java - 在运行时更改实现/类

algorithm - 从堆中最小的 log n 项创建排序数组

c++ - 使用模板将堆栈实现为链表时出现 "symbols not found"错误

c - 使用 sscanf 从数字中读取数字

java - 实现 Kruskal 算法时测试电路

c - 终止C语言程序

c - 理解这个示例程序

c++ - 为什么我不能创建 std::ifstreams 的 std::stack?

c - 从文件中读取单词并将其作为字符指针返回

objective-c - 在内存中保存一个 c 数组,以便以后可以使用指针访问它