给我用cplus语言写一个栈
时间: 2024-05-05 16:19:04 浏览: 168
算法:我用C ++实现的几种算法和数据结构(必要时贷给其他人)
好的,这是一个简单的 C++ 栈的实现:
```cpp
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int top;
int data[MAX_SIZE];
public:
Stack() {
top = -1;
}
bool isEmpty() {
return top == -1;
}
bool isFull() {
return top == MAX_SIZE - 1;
}
void push(int value) {
if(isFull()) {
cout << "Stack is full." << endl;
return;
}
top++;
data[top] = value;
}
int pop() {
if(isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
int value = data[top];
top--;
return value;
}
};
int main() {
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << s.pop() << endl;
cout << s.pop() << endl;
cout << s.pop() << endl;
cout << s.pop() << endl;
return 0;
}
```
阅读全文