(原)剑指offer之栈和队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
设两个栈为stack1,stack2;
1:首先想到最简单的方法:是入栈时将数据压入stack1,出栈时将stack1中的元素出栈压入stack2,在将stack2栈顶元素弹出,再将stack2中的剩余元素重新压入stack1,
这种方法很低效可想而知。
2:改进一下:入栈时检查stack1,如果stack1为空则元素全在stack2中,所以将stack2中的元素压入stack1中(记得检查stack2是否为空),再将元素入栈,如果stack1不为空直接将元素压入栈,同样出栈时检查stack2,如果为空将stack1中的元素压入stack2再将栈顶元素出栈,如果不为空直接将栈顶元素出栈。
 
方法2的c++代码实现:
 
 
class Solution
{
public:
    void push(int node) {
        if (stack1.size() != 0) stack1.push(node);
        else{
            int n = (int)stack2.size();
            for (int i = 0; i < n; i++){
                stack1.push(stack2.top());
                stack2.pop();
            }
            stack1.push(node);
        }
    }
    
    int pop() {
        if (stack2.size() != 0) {
            int temp = stack2.top();
            stack2.pop();
            return temp;
        }
        else {
            int n = (int)stack1.size();
            for (int i = 0; i < n - 1; i++){
                stack2.push(stack1.top());
                stack1.pop();
            }
            int temp =stack1.top();
            stack1.pop();
            return temp;
        }
        
    }
    
    
private:
    stack<int> stack1;
    stack<int> stack2;
};

在网上找到一种更高效的方法:入栈时直接将元素压入stack1,出栈时检查stack2,如果为空将stack1中的元素压入stack2,如果不为空直接将stack2栈顶元素出栈,很巧妙

 

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }
    
    int pop() {
        int temp;
        if (!stack2.empty()) {
            temp = stack2.top();
            stack2.pop();
            return temp;
        }
        else {
            int n = stack1.size();
            for (int i = 0; i < n; i++){
                stack2.push(stack1.top());
                stack1.pop();
            }
            temp = stack2.top();
            stack2.pop();
            return temp;
        }
    }

 

posted @ 2015-05-31 15:56  孤光一点莹  阅读(131)  评论(0编辑  收藏  举报