代码随想录 (五)栈和队列

1栈与队列基础知识待看

2.用栈实现队列
题意有说操作是有效的,不用去判断非法的情况
代码随想录 (五)栈和队列_第1张图片

class MyQueue {
public:
	stack<int> stIn;
	stack<int> stOut; 
    MyQueue() {

    }
    
    void push(int x) {
    	stIn.push(x);
    }
    
    //出队并返回该元素 
    int pop() {
    	if (stOut.empty()) {//只有出栈的栈为空,才把全部元素放到出栈的栈
    		while(!stIn.empty()) {  
    			stOut.push(stIn.top()); 
    			stIn.pop();
			}
		}
		int result = stOut.top(); //stOut不空 直接出栈 
		stOut.pop();
		return result; 
    }
    
    int peek() {  //直接函数复用 因为在同个类里面 直接this 可以在同一个类中重复使用代码 
		int res = this->pop();
		stOut.push(res);
		return res;
    }
    
    bool empty() {
    	return stIn.empty() && stOut.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

3.用队列实习栈

4.有效的括号

class Solution {
public:
    bool isValid(string s) {
    	if (s.size() % 2 != 0) return false;
		stack<char>  st;
		for (int i = 0; i < s.size(); i++) {
			if (s[i] == '(') {
				st.push(')');
			} else if (s[i] == '[') {
				st.push(']');
			} else if (s[i] == '{') {
				st.push('}');
			}
			else if (st.empty() || st.top() != s[i]) return false;
			else st.pop();
		}
		return st.empty(); //遍历完了 就看栈为不为空了 
    }
};

5.删除字符串中的所有相邻重复项
法1:

class Solution {
public:
    string removeDuplicates(string S) {
			stack<char> st;
    	for(char s : S) {
    		if (st.empty() || s != st.top()) {
    			st.push(s);
			} else {
				st.pop();  //遍历到的字符与栈顶相等 则出栈 
			}
		}
		string result =""; //定义并初始化为空字符串
		while(!st.empty()) {
			result += st.top();   
			st.pop();
		} 
		reverse (result.begin(), result.end());
		return result;
    }
};

法二://这种不懂 看视频

class Solution {
public:
    string removeDuplicates(string S) {
        string result;
        for(char s : S) {
            if(result.empty() || result.back() != s) {
                result.push_back(s);
            }
            else {
                result.pop_back();
            }
        }
        return result;
    }
};

6.逆波兰表达式求值

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
    	stack<long long> st;
    	for (int i = 0; i < tokens.size(); i++) {
    		if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
    			long long num1 = st.top();
    			st.pop();
    			long long num2 = st.top();
    			st.pop();
    			if (tokens[i] == "+") st.push(num2 + num1);
    			if (tokens[i] == "-") st.push(num2 - num1);
    			if (tokens[i] == "*") st.push(num2 * num1);
    			if (tokens[i] == "/") st.push(num2 / num1);
			} else {
				st.push(stoll(tokens[i])); //stoll 是 C++ 中用于将字符串转换为长长整型(long long int)的函数。
			}
		}
		
		int result = st.top();
		st.pop();
		return result;
    }
};

你可能感兴趣的:(代码随想录笔记,笔记)