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;
    }
};


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