剑指offer---栈系列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Android_chunhui/article/details/88016186
  1. 能查最小值的栈

题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

思路:
定义一个data栈和mins栈分别存放原始数据和最小值,注意两个栈长度相同。当push时如果值小于mins栈顶数字就入栈否则入mins的栈顶元素,这样就保证了mins栈顶元素一直是data栈中最小的。pop时一起出栈。
比如,data中依次入栈,5, 4, 3, 8, 10, 11, 12, 1
则min依次入栈,5, 4, 3,3,3, 3, 3, 1

class Solution {
public:
	void push(int value) {
		data.push(value);
		if (mins.empty())
			mins.push(value);
		else {
			if (mins.top() > value)
				mins.push(value);
			else
				mins.push(mins.top());
		}
	}
	void pop() {
		data.pop();
		mins.pop();
	}
	int top() {
		return data.top();
	}
	int min() {
		return mins.top();
	}
private:
	stack<int> data;
	stack<int> mins;
};

  1. 验证栈的弹出顺序

题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:
只需要验证给出的弹出序列能否有压入栈生成即可。在每次压栈前检查栈顶元素是否和出栈序列中元素,循环检测直到不相等为止.如果数据全部押入,那么栈中剩余元素出栈顺序就应该和剩余的出战顺序一样,如果有不一样则表示序列不匹配。

class Solution {
public:
    bool IsPopOrder(vector<int> pushV, vector<int> popV) {
        stack<int> st;
        int j = 0;
        for (int i = 0; i < pushV.size(); ++i)
        {
            while (!st.empty() && st.top() == popV[j])
            {
                st.pop();
                ++j;
            }
            st.push(pushV[i]);
        }
        while(!st.empty() && st.top()==popV[j])
        {
            st.pop();
            ++j;
        }
        if (!st.empty()) return false;
        return true;
}
};
  1. 两个栈实现队列

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:
入栈时押入stack1,出站时为了得到stack1栈底元素,必须先将stack1数据全部转移到stack2中,出完站之后再将stack2剩余元素押回stack1中。

class Solution
{
public:
    void push(int node) {
		stack1.push(node);
	}

	int pop() {
		while (!stack1.empty())
		{
			stack2.push(stack1.top());
			stack1.pop();
		}
		int v = stack2.top();
		stack2.pop();
        while (!stack2.empty())
		{
			stack1.push(stack2.top());
			stack2.pop();
		}
		return v;
	}

private:
    stack<int> stack1;
    stack<int> stack2;
};

猜你喜欢

转载自blog.csdn.net/Android_chunhui/article/details/88016186