最近在学习数据结构,栈在这里总结一下c++实现的栈几种方法:1.使用数组这是几种方法里面最为简单的方法,直接放代码:
“`
include
using namespace std;
template
class arraystack {
public:
arraystack();
~arraystack();
t peek();
t top();
t pop();
void push(t a);
int size();
int is_empty();
private:
int count;
t *arr;
};
template
arraystack::arraystack() {
count = 0;
arr = new t[100];
if (!arr) {
cout << “arr maloc error” << endl;
}
}
//销毁~栈
template
arraystack::~arraystack() {
if (arr) {
delete []arr;
arr = NULL;
}
}
//将value压入栈中
template
void arraystack ::push(t a) {
arr[count] = a;
count++;
}
template
t arraystack::pop() {
if (count >0) {
count–;
return arr[count];
}
else {
cout << "the stack is empty" << endl;
}
}
template
//返回栈顶元素
t arraystack ::peek() {
if (count) {
return arr[count - 1];
}
return NULL;
}
//返回栈的长度
template
int arraystack::size() {
return count;
}
//判断栈是否为空
template
int arraystack ::is_empty() {
return count == 0;
}
int main() {
arraystack *exe = new arraystack();
exe->push(1);
exe->push(2);
exe->push(3);
exe->push(4);
cout << “exe->size()=” << exe->size() << endl;
cout << "exe->peek()="<<exe->peek() << endl;
`
hile (!exe->is_empty()) {
cout << “exe->pop():”<pop() << endl;
}
}
“`后续再补上单链表以及双链表实现栈的代码