[LeetCode] 232、用栈实现队列

题目描述

使用栈实现队列的下列操作:

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • empty() – 返回队列是否为空。

参考代码

// 该题解有一些异常输入没处理,可用“全局变量”的方式处理一下就好
class MyQueue{
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    /** Push element x to the back of queue. */
    void push(int x){
        stack1.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop(){
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        
        if(!stack2.empty()){
            int res = stack2.top();
            stack2.pop();
            return res;
        }
        return -1;
    }
    
    /** Get the front element. */
    int peek() {
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        
        if(!stack2.empty())
            return stack2.top();
        return -1;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(stack1.empty() && stack2.empty())
            return true;
        else
            return false;
    }

private:
    stack<int> stack1;  // 进队列
    stack<int> stack2;  // 出队列
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

补充:用队列实现栈(参考

template<typename T> class CStack
{
public:
	CStack(void);
	~CStack(void);
 
	void appendTail(const T& node);
	T deleteHead();
 
private:
	queue<T> q1;
	queue<T> q2;
};
 
template<typename T>
void CStack<T>::appendTail(const T& node)//实现栈元素的插入
{
	//数据的插入原则:保持一个队列为空,一个队列不为空,往不为空的队列中插入元素
	if (!q1.empty())
	{
		q1.push(node);
	}
	else
	{
		q2.push(node);
	}
}
 
template<typename T>
T CStack<T>::deleteHead()//实现栈元素的删除
{
	int ret = 0;
	if (!q1.empty())
	{
		int num = q1.size();
		while (num > 1)
		{
			q2.push(q1.front());
			q1.pop();
			--num;
		}
		ret = q1.front();
		q1.pop();
	}
	else
	{
		int num = q2.size();
		while (num > 1)
		{
			q1.push(q2.front());
			q2.pop();
			--num;
		}
		ret = q2.front();
		q2.pop();
	}
	return ret;
}

发布了402 篇原创文章 · 获赞 588 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/104005807