在 LIFO 数据结构中,将首先处理添加到队列
中的最新元素
。
与队列不同,栈是一个 LIFO 数据结构。通常,插入操作在栈中被称作入栈 push
。与队列类似,总是在堆栈的末尾添加一个新元素
。但是,删除操作,退栈 pop
,将始终删除
队列中相对于它的最后一个元素
。
栈的实现
栈的实现比队列容易。动态数组
足以实现堆栈结构。这里我们提供了一个简单的实现供你参考:
#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