【剑指09】用两个栈实现队列

方法一:辅助栈:时间O(n),空间O(n)

题解:用两个栈,一个栈用来插入数据,另一个栈用来删除数据

class CQueue {
    
    
public:
    stack<int> stack1;
    stack<int> stack2;
    CQueue() 
    {
    
    
        while (!stack1.empty())
        {
    
    
            stack1.pop();
        }
        while (!stack2.empty())
        {
    
    
            stack2.pop();
        }
    }
    
    void appendTail(int value) 
    {
    
    
        stack1.push(value);
    }
    
    int deleteHead() 
    {
    
    
        if (stack2.empty())
        {
    
    
            while (!stack1.empty())
            {
    
    
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        if (stack2.empty())
            return -1;
        int deleteitm = stack2.top();
        stack2.pop();
        return deleteitm;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/112412035