目录
例1:使用队列实现栈(easy 栈、队列)
class MyStack {
public:
MyStack() {
}
void push(int x) {
std::queue<int> temp_queue;
temp_queue.push(x);
while (!_data.empty()) {
temp_queue.push(_data.front());
_data.pop();
}
while (!temp_queue.empty()) {
_data.push(temp_queue.front());
temp_queue.pop();
}
}
//下面的操作,栈和队列一致
int pop() {
int x = _data.front();
_data.pop();
return x;
}
int top() {
return _data.front();
}
bool empty() {
return _data.empty();
}
private:
std::queue<int>_data;
};
例2:使用栈实现队列(easy 栈、队列)
class MyQueue {
public:
MyQueue() {
}
//双栈
void push(int x) {
input_stack.push(x);
}
int pop() {
adjust();
int x = output_stack.top();
output_stack.pop();
return x;
}
int peek() {
adjust();
return output_stack.top();
}
bool empty() {
return (input_stack.empty() && output_stack.empty());
}
private:
void adjust() {
if (!output_stack.empty()) {
return;
}
while (!input_stack.empty()) {
output_stack.push(input_stack.top());
input_stack.pop();
}
}
std::stack<int> input_stack;
std::stack<int> output_stack;
};
例3:包含min函数的栈(easy 栈)
用一个单独的栈来存放最小值
class MinStack {
public:
MinStack() {
}
void push(int x) {
_data.push(x);
if (_min.empty()) {
_min.push(x);
}
else {
if (x > _min.top()) {
x = _min.top();
}
_min.push(x);
}
}
void pop() {
_min.pop();
_data.pop();
}
int top() {
return _data.top();
}
int getMin() {
return _min.top();
}
private:
std::stack<int> _data;
std::stack<int> _min;
};
例4:合法的出栈序列(medium 栈、队列)
题目:
思路:
bool check_is_valid_order(std::queue<int>& order) {
std::stack<int> s;//s为模拟栈
int n = order.size();
for (int i = 0; i <= n; i++) {
s.push(i);
while (!s.empty() && s.top() == order.front()) {
s.pop();
order.pop();
}
}
if (!s.empty()) {
return false;
}
return true;
}
例5:简单的计算器(hard 栈)
例6:数组中第K大的数(easy 堆)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int> > q;
for (int i = 0; i < nums.size(); i++) {
if (q.size() < k) {
q.push(nums[i]);
}
else if (q.top() < nums[i]) {
q.pop();
q.push(nums[i]);
}
}
return q.top();
}
};