c++栈的实现

本文介绍了如何使用C++实现栈,首先从最简单的数组方法开始,详细讲解了数组栈的创建、压入、弹出、查看栈顶元素、获取栈的大小及检查栈是否为空的操作。提供了完整的代码示例。后续将继续补充单链表和双链表实现栈的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习数据结构,栈在这里总结一下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;
}

}
“`后续再补上单链表以及双链表实现栈的代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值