Simple data structure
1 min readFeb 13, 2020
155. Min Stack
https://leetcode.com/problems/min-stack/
Use two stacks to have O(1) complexity with O(n) space.
class MinStack {
int size_;
vector<int>stack, min_values;
public:
/** initialize your data structure here. */
MinStack(): size_(0){
min_values.push_back(INT_MAX);
}
void push(int x) {
stack.push_back(x);
min_values.push_back(min(min_values.back(),x));
size_++;
}
void pop() {
if(size_==0)return;
stack.pop_back();
min_values.pop_back();
size_--;
}
int top() {
if(size_==0)return -1;
return stack.back();
}
int getMin() {
return size_==0?0:min_values.back();
}
};/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
232. Implement Queue using Stacks
https://leetcode.com/problems/implement-queue-using-stacks/
class MyQueue {
stack<int> in_, out_;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
in_.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res = peek();
out_.pop();
return res;
}
/** Get the front element. */
int peek() {
if(out_.empty())
while(!in_.empty())
out_.push(in_.top()), in_.pop();
return out_.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return in_.empty() && out_.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();
*/