面试题 03.05. 栈排序

面试题 03.05. 栈排序

思路:2个栈,data存储顺序,help帮助data存储排序

class SortedStack {
public:
    stack data, help;
    SortedStack() {

    }
    
    void push(int val) {
        if(data.size()==0 || val<=data.top()){data.push(val); return;}//直接往data上放
        while(data.size()!=0 && val>data.top()){
            help.push(data.top());
            data.pop();
        }
        data.push(val);
        while(help.size()){
            data.push(help.top());
            help.pop();
        }
    }
    
    void pop() {
        if(data.size()!=0)
            data.pop();
    }
    
    int peek() {
        if(data.size()!=0)
            return data.top();
        return -1;
    }
    
    bool isEmpty() {
        return data.empty();
    }
};

 

你可能感兴趣的:(面试题 03.05. 栈排序)