参考LeetCode教程
基本思想
后入先出(LIFO)的数据结构。

基本实现
通过动态数组实现栈的结构。
#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;
}
}
用法
cpp有现成的库,用的时候初始化就行,入栈、出栈操作。
#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;
}
整一下,就是以下内容:
stack<type> a; # 初始化
s.push(value); # 后加
s.pop(); # 后减
s.empty(); # 判断空否
s.top(); # 返回栈顶元素
s.size(); # 返回栈元素个数
想首先处理最后一个元素时,栈将是最合适的数据结构。
本文深入解析栈数据结构的基本概念与特性,详细介绍了使用C++动态数组实现栈的方法,包括push、pop、top等核心操作,并通过示例代码展示了栈的实际应用。此外,文章还探讨了栈在深度优先搜索(DFS)算法中的关键作用。
22万+

被折叠的 条评论
为什么被折叠?



