Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 这个程序是要在O(1)复杂度的堆栈中获得最小值吗?_C_Data Structures - Fatal编程技术网

C 这个程序是要在O(1)复杂度的堆栈中获得最小值吗?

C 这个程序是要在O(1)复杂度的堆栈中获得最小值吗?,c,data-structures,C,Data Structures,我已经实现了push-pop和get-minimum-in-O1复杂性。我在C++中看到了很多解决方案。这是C本身的一个实现。下面的程序正确吗 #include <stdio.h> #include <stdlib.h> int stack[15],aux[15]; int top=-1,count=-1,aux_count=-1,temp_aux=-1; void push_auxilary(int ele) { aux[++aux_count] = ele; } vo

我已经实现了push-pop和get-minimum-in-O1复杂性。我在C++中看到了很多解决方案。这是C本身的一个实现。下面的程序正确吗

#include <stdio.h>
#include <stdlib.h>
int stack[15],aux[15];
int top=-1,count=-1,aux_count=-1,temp_aux=-1;
void push_auxilary(int ele)
{
aux[++aux_count] = ele;
}
void push_stack(int ele)
{
    stack[++top]=ele;
}
void push(int ele)
{
    if(top < 0 && aux_count < 0)
    {
        push_auxilary(ele);
        push_stack(ele);
    }
    else
        {
            if(ele > aux[aux_count])
            {
                push_auxilary(aux[aux_count]);
                push_stack(ele);
            }
            else
            {
                push_stack(ele);
                push_auxilary(ele);
            }
        }
}
int pop_stack()
{
    return stack[top--];
}
int pop_auxilary()
{
    return aux[aux_count--];
}
int pop()
{
    int a = pop_stack();
    pop_auxilary();
    return a;
}
void display()
{
    for (int i = top; i >= 0; i--)
    {
        printf("%d\n",stack[i]);
        /* code */
    }
}
int get_min()
{
    return aux[aux_count];
}
int main(int argc, char const *argv[])
{
    int i=0;
    push(5);
    push(9);
    push(1);
    push(6);
    push(1);
    push(54);
    push(34);
    push(9);
    push(3);
    push(4);
    push(7);
    push(12);
    push(02);
    printf("the %d\n",get_min() );
    for (i = aux_count; i >= 0; i--)
    {
        printf("%d\n",aux[i]);
    }
    return 0;
}

看起来它确实在O1中完成了任务。算法正确,但从代码重用的角度来看很糟糕。

你那里的奇特缩进,真的很讨人喜欢。除了打印功能,对我来说似乎是O1次。没有循环或递归意味着恒定的时间。@adam ya我也这么认为。我的疑问是,我所做的比较的数量也会影响复杂性,对吗?这个问题似乎离题了,因为它属于“不,比较不会影响时间复杂性”。将时间复杂性视为操作的数量。您的比较运行在O2或O4或O5或其他环境中,而您的显示循环运行在O2n环境中。时间复杂性删除了前导常量,并将其替换为1,因为从长远来看,单个操作的数量并不重要。因为您的程序只有一个操作,没有循环,所以它以恒定的时间运行。第一个堆栈是主堆栈,另一个堆栈是以o1复杂度而不是复杂度跟踪最小堆栈。如果没有额外的堆栈数据结构,您永远无法在o1中找到最小值。