Implement Stack using Queues - LeetCode 225

题目描述:
Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

Hide Tags Data Structure

分析:
由于栈是先进后出,队列是先进先出,两者出栈顺序是相反的,因此,因此两个队列来实现一个栈,一个作为中转队列,一个是目标队列,二者不断交换角色。过程描述如下:
在用队列实现栈的出栈操作时,需要删除队队尾的元素,那么得将目标队列的非队尾元素出队列存放到中转队列中,然后出队原队尾元素。此时目标队列和中转队列角色互换。
对于压栈操作,直接将元素放入目标队列(非空)队尾,若两个队列都为空,那么随便选择其中一个作为目标的队列即可。
对于判空,如过两个队列都为空,那么返回true,否则返回false。
对于top操作,直接返回非空队列的队尾元素即可。

思路还是挺简单的,以下是C++实现代码:

/**///////////////////////////0ms*/
class Stack {
public:
    queue<int> q1,q2;

    // Push element x onto stack.
    void push(int x) {
	if(q1.empty() && q2.empty() || !q1.empty())
	    q1.push(x);
	else 
	    q2.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
	int top = 0;
        if(!Stack::empty()){
	    if(!q1.empty()){
		int n = q1.size()-1;
		while(n--)
		    {
			q2.push(q1.front());
			q1.pop();
		    }
			q1.pop();
		}
	    else{
		int n = q2.size()-1;
		while(n--)
		    {
			q2.push(q2.front());
			q2.pop();
		}
		q2.pop();
	    }
        }
    }

    // Get the top element.
    int top(){
        if(!Stack::empty()){
	    if(!q1.empty())
		return q1.back();
	    else
		return q2.back();
	}
    }

    // Return whether the stack is empty.
    bool empty() {
	if(q1.empty() && q2.empty())
	    return true;
	return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章