目录
一、后入先出的数据结构
// C++ implementation
#include <iostream>
class MyStack {
private:
vector<int> data; // store elements
public:
/** Insert an element into the stack. */
void push(int x) {
data.push_back(x);
}
/** Checks whether the queue is empty or not. */
bool isEmpty() {
return data.empty();
}
/** Get the top item from the queue. */
int top() {
return data.back();
}
/** Delete an element from the queue. Return true if the operation is successful. */
bool pop() {
if (isEmpty()) {
return false;
}
data.pop_back();
return true;
}
};
int main() {
MyStack s;
s.push(1);
s.push(2);
s.push(3);
for (int i = 0; i < 4; ++i) {
if (!s.isEmpty()) {
cout << s.top() << endl;
}
cout << (s.pop() ? "true" : "false") << endl;
}
}
参考文献:https://leetcode-cn.com/leetbook/read/queue-stack/ghqur/
二、栈 - 用法
// C++ implementation
#include <iostream>
int main() {
// 1. Initialize a stack.
stack<int> s;
// 2. Push new element.
s.push(5);
s.push(13);
s.push(8);
s.push(6);
// 3. Check if stack is empty.
if (s.empty()) {
cout << "Stack is empty!" << endl;
return 0;
}
// 4. Pop an element.
s.pop();
// 5. Get the top element.
cout << "The top element is: " << s.top() << endl;
// 6. Get the size of the stack.
cout << "The size is: " << s.size() << endl;
}
参考文献:https://leetcode-cn.com/leetbook/read/queue-stack/gxtls/
三、最小栈
3.1 题目要求
3.2 解决过程
个人实现
法一:基于内置列表类型。getMin() 操作复杂度太高使整体效率不足,需要改进其实现方式。
2020/08/30 - 15.99% (716ms)
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.minstack = []
def push(self, x: int) -> None:
self.minstack.append(x) # 复杂度 O(1)
def pop(self) -> None:
self.minstack.pop() # 复杂度 O(1)
def top(self) -> int:
return self.minstack[-1] # 复杂度 O(1)
def getMin(self) -> int:
return min(self.minstack) # 复杂度 O(n)
官方实现与说明
class MinStack:
def __init__(self):
self.stack = [] # 主栈
self.min_stack = [math.inf] # 辅