栈空栈满的判定
栈是一种先进后出的数据结构,可以通过数组或链表来实现。栈有两种状态,即空栈和满栈。
-
空栈判定:当栈中没有任何元素时,即为空栈。可以通过判断栈顶指针是否为-1来判断栈是否为空。
-
满栈判定:当栈中的元素个数达到栈的最大容量时,即为满栈。可以通过判断栈顶指针是否等于栈的最大容量减1来判断栈是否为满栈。
下面是一个使用数组实现的栈的示例代码:
#include <iostream>
using namespace std;
#define MAX_SIZE 100
class Stack {
private:
int top; // 栈顶指针
int arr[MAX_SIZE]; // 使用数组实现栈
public:
Stack() {
top = -1; // 初始化栈顶指针为-1,表示空栈
}
// 判断栈是否为空
bool isEmpty() {
return top == -1;
}
// 判断栈是否为满栈
bool isFull() {
return top == MAX_SIZE - 1;
}
// 入栈
void push(int val) {
if (isFull()) {
cout << "Stack is full." << endl;
return;
}
arr[++top] = val; // 先将栈顶指针加1,再将元素入栈
}
// 出栈
int pop() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return arr[top--]; // 先返回栈顶元素,再将栈顶指针减1
}
// 获取栈顶元素
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return arr[top]; // 返回栈顶元素
}
};
int main() {
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "Stack is empty? " << (s.isEmpty() ? "Yes" : "No") << endl;
cout << "Stack is full? " << (s.isFull() ? "Yes" : "No") << endl;
cout << "Top element: " << s.peek() << endl;
cout << "Pop element: " << s.pop() << endl;
cout << "Pop element: " << s.pop() << endl;
cout << "Pop element: " << s.pop() << endl;
cout << "Pop element: " << s.pop() << endl;
cout << "Stack is empty? " << (s.isEmpty() ? "Yes" : "No") << endl;
cout << "Stack is full? " << (s.isFull() ? "Yes" : "No") << endl;
return 0;
}
输出结果:
Stack is empty? No
Stack is full? No
Top element: 3
Pop element: 3
Pop element: 2
Pop element: 1
Stack is empty? Yes
Stack is full? No
``
原文地址: http://www.cveoy.top/t/topic/hAiE 著作权归作者所有。请勿转载和采集!