建立一个C++类 堆栈 不使用vector
时间: 2023-09-16 14:13:47 浏览: 49
好的,我可以帮你设计一个简单的堆栈类。以下是一个基本的堆栈类的示例:
```cpp
class Stack {
private:
int* data;
int topIndex;
int capacity;
public:
Stack(int size) {
data = new int[size];
topIndex = -1;
capacity = size;
}
~Stack() {
delete[] data;
}
bool isEmpty() {
return topIndex == -1;
}
bool isFull() {
return topIndex == capacity - 1;
}
void push(int value) {
if (isFull()) {
cout << "The stack is full." << endl;
return;
}
topIndex++;
data[topIndex] = value;
}
int pop() {
if (isEmpty()) {
cout << "The stack is empty." << endl;
return -1;
}
int value = data[topIndex];
topIndex--;
return value;
}
};
```
在这个类中,我们使用一个动态分配的整数数组来存储堆栈中的元素。我们还使用一个变量来跟踪堆栈顶部的位置。该堆栈的容量在创建时被指定,并且不能动态更改。
我们还实现了以下函数:
- `isEmpty()`:检查堆栈是否为空。
- `isFull()`:检查堆栈是否已满。
- `push(int value)`:将值推入堆栈。
- `pop()`:从堆栈中弹出一个值。
请注意,此实现仅适用于整数类型。如果要将其用于其他类型,可以将 int 替换为模板类型 T,并相应地更改数组和函数的定义。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)