Implementation of queue with 2 stack

本文介绍了如何利用两个栈来实现队列的功能,包括原始想法、改进方法(懒更新)、代码实现以及时间复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    如何用两个栈来实现一个队列呢?

    一种很直接的想法是先push 到stack1的,然后stack1 整个再push到stack2,这样的话stack2就是最先的element在最上面了。每次push新元素,先stack2移到stack1,然后push新元素到stack2,再将stack1的元素push回stack2,pop时直接pop stack2就行,但是这样push的操作就不是O(1)的,而是O(n). 而且每添加一个元素都需要移动所有的元素。

   改进:lazy update

   push时push到stack1,pop时从stack2取,如果stack2为空,则将stack1的push到stack2中。这样平均下来,push和pop都是O(1)的。pop为什么也是O(1)? 因为假设这次pop stack2没有element了,那么从stack1 取了m个到stack2,每个element计一次操作,但是接下来的m-1次pop是不需要取了,只需要一次pop就行,相当于每个element再加上一次操作。总共就是每个element 2次操作就pop出来了,所以时间是O(1).


/**
 * @file QueueWith2Stacks3-5.cpp
 * @Brief This queue is implemented with the help of two stack.
 * @author  Brian 
 * @version 1.0
 * @date 2013-08-29
 */

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>

using namespace std; 

template<class T>
class Queue{
    stack<T> s1;
    stack<T> s2;
    public:
        void push(const T& val){
            s1.push(val);
        }
        T& front(){
            if(s2.empty()){
                while(!s1.empty()){
                    s2.push(s1.top());
                    s1.pop();
                }
            }
            return s2.top();
        }
        void pop(){
            if(s2.empty()){
                while(!s1.empty()){
                    s2.push(s1.top());
                    s1.pop();
                }
            }
            s2.pop();
        }
        size_t size(){
            return s1.size()+s2.size();
        }
};

int main(){
    Queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);
    cout<<q.size()<<endl;
    cout<<q.front()<<endl;
    q.pop();
    cout<<q.front()<<endl;
    q.pop();
    cout<<q.front()<<endl;
    return 0;
}


The goal of task 1 The goal of this exercise is to implement a Stack data structure. The implementation must pass all the tests included in the exercise. Time complexity requirements: capacity(): O(1). push(): O(1), except for when reallocation must be done: O(n). pop(): O(1). peek(): O(1). size(): O(1). isEmpty(): O(1). toString(): O(n). clear(): O(1). When implementing clear() you may decide yourself if you want to keep the current capacity or will the capacity be the default capacity of a queue. Note that the method toString() in this and later execises must be implemented using Java StringBuilder, not by using the String by modifying and appending to a String object. When handling large amounts of data elements, with String, this is hundreds of times slower than using StringBuilder. This has already been implemented for you. Prerequisites You have all the tools installed and working. This was tested in the 00-init exercise of the course. If you haven't done that yet, do it now. Instructions An overview of the classes in this exercise is shown in the UML class diagram below. Note that in this task, you only work with the StackImplementation class. The class ParenthesisTChecker.java and StackFactory.createCharacterStack() are not needed until you start working with the additional tasks. If you want to, you may crete your own main app file, for example in src/main/java/oy/tol/tra/Main.java, where you may implement your own main() method to experiment with your stack implementation. However, the main goal of the exercise is to pass all the unit tests. Do not implement main() method to data structure classes or test classes! Before delivery, remove all main functions an any unnrcessary test code. UML class diagram You should implement the interface StackInterface in the StackImplementation.java which is already created for you and located in this project's src/main/java/oy/tol/tra/ directory! Note that the StackImplementation uses E template parameter for the StackInterface: public class StackImplementation<E> implements StackInterface<E> { So the stack is a generic (template) class. Make sure to read the StackInterface documentation (the comments in the code) carefully so that your implementation follows the interface documentation. Obviously you need to know how stacks work in general, so check out the course lectures and other material on stack data structures. In this exercise, you use the Java plain array as the internal data structure for holding the elements: private Object [] itemArray; Since all Java classes inherit from Object, we can create an array of Objects for the elements. In the StackImplemention, constructors, follow the code comments and allocate the array of elements, in addition to other things you need to implement: itemArray = new Object[capacity]; Make sure to implement reallocating more room in the StackImplementation internal array if array is already full, when push() is called! After you have implemented your stack class methods, you can see that it is already instantiated for you in StackFactory.createIntegerStack(). After this, you are ready to test your implementation.
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值