一、数组实现栈
1.1 栈声明
1.2 方法实现
1.3 测试结果及代码
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <climits>
#include <iomanip>
using namespace std;
class Stack {
private:
int *_data;
int _size;
int _capcity;
public:
Stack(int capcity);
virtual ~Stack() {
delete[] _data; _data = NULL; }
int top();
void push(int x);
int pop();
int size() const {
return _size; }
void clear() {
_size = 0; }
bool isEmpty() const {
return !_size; }
};
Stack::Stack(int capcity) {
if (capcity < 0) {
cerr << "初始化长度小于0,初始化失败!\n";
exit(-1);
}
_data = new int[capcity];
_size = 0;
_capcity = capcity;
}
int Stack::top() {
if (_size == 0) {
cout << "栈为空,不能pop!现在返回-1\n";
return -1;
}
return _data[_size - 1];
}
void Stack::push(int x) {
if (_size == _capcity) {
cout << "\n栈满,不能push\n";
return;
}
_data[_size++] = x;
}
int Stack::pop() {
if (_size == 0) {
cout << "栈为空,不能pop!现在返回-1\n";
return -1;
}
return _data[--_size];
}
int main (int argc, char* argv[]) {
srand(time(NULL));
const int test_time = 15;
Stack s(5);
for (int cnt = 0; cnt < test_time; ++cnt) {
int i = rand