Data structures 从两堆栈队列中退出队列的最坏情况时间复杂度是多少?

Data structures 从两堆栈队列中退出队列的最坏情况时间复杂度是多少?,data-structures,stack,queue,big-o,Data Structures,Stack,Queue,Big O,我的作业要求我确定以下算法的最坏运行时间。排队很容易。这是不变的(我希望,否则我会觉得自己很愚蠢) 第二个问题令人困惑。昨天我问了一个类似的问题,得到了很多非常有用的答案。我会尽力的 Algorithm enqueue(o) in stack.push(o) Algorithm dequeue() while (! in stack.isEmpty()) do // this just checks for an empty stack, so O(1)

我的作业要求我确定以下算法的最坏运行时间。排队很容易。这是不变的(我希望,否则我会觉得自己很愚蠢)

第二个问题令人困惑。昨天我问了一个类似的问题,得到了很多非常有用的答案。我会尽力的

Algorithm enqueue(o)
    in stack.push(o)

Algorithm dequeue()
    while (! in stack.isEmpty()) do    // this just checks for an empty stack, so O(1)
        out stack.push(in stack.pop()) // this do loop runs for as many times as values in the stack, so it is O(N)

    if (out stack.isEmpty()) then
        throw a QueueEmptyException    // this is just an exception, so I assume it is O(1) 

    return_obj ←  out stack.pop()      // I think the rest of the program is linear.
                                       // Although without actually coding it out, I'm not 100% sure I even understand what it does.
    while (! out stack.isEmpty()) do

    in stack.push(out stack.pop())
    return return_obj;

一种方法是计算推送和弹出的次数。如果您的队列中有n个元素,那么实现将执行n次推送和n次弹出操作,以将
in
传输到
out
。然后,它进行一次弹出以去除最后一个元素,然后再进行n-1次推送,再进行n-1次弹出以将
放回
中。这是一个Θ(n)推和弹出的总数。每次推送和弹出需要Θ(1)个时间(或者至少n次推送和n次弹出需要Θ(n)个时间),因此堆栈操作完成的总工作量为Θ(n)。还有O(1)个额外的工作要做,比如错误处理等。因此,完成的总工作是Θ(n)


希望这有帮助

从链表前面删除节点需要固定的时间。但是,查找链表的最后一个节点需要线性时间(除非我们小心地维护对它的引用)。

这看起来不像C++我认为它是伪代码。问题中的实现与您描述的不同,即出列总是将元素从
in
移动到
out
,然后再移动回来。这导致了排队的最佳情况复杂性为O(n)。