前言
实现思想:向堆中申请固定的内存块来实现,栈在内存中是一块连续的内存。
栈的成员包括:
容量: size
栈顶标识:top
栈的内存地址: stack
push && pop && current 接口
对于push入栈操作,我本来传引用进去,但是考虑会有外部把栈内数据修改的风险。决定还是传值最好,所有数据全部保存到栈中统一管理。
bool push(T& value) {}
bool push(T value) {}
对于pop ,想一个函数返回两个返回值,决定传进去引用。
bool pop(T& value) {}
对于current()取栈顶值,一开始是返回引用类型,考虑会有外部把栈内数据修改的风险。决定返回值类型。
T& current() {}
T current() {}
stack 类代码
template<class T>
class stack {
private:
int m_capcity;
int m_top;
T* m_stack; //栈的空间 :指针指向一个固定大小的内存空间
public:
stack(int size) :m_top(0) {
m_capcity = size;
m_stack = new T[m_capcity]();
}
~stack() {
delete m_stack;
m_stack = nullptr;
}
//弃用
//bool push(T& value) {
// if (m_top >= m_capcity)
// {
// assert(false);
// return false;
// }
// m_stack[m_top] = value;
// m_top++;
//}
//设计成值传递 所有数据全部保存到栈中 统一管理
bool push(T value) {
if (m_top >= m_capcity)
{
assert(false);
return false;
}
m_stack[m_top] = value;
m_top++;
}
bool pop(T& value) {
if (!m_top)
{
assert(false);
return false;
}
value = m_stack[--m_top];
return true;
}
//弃用
////返回引用 外部会修改栈的内容不安全
//T& current() {
// if (!m_top)
// assert(false);
// int temp = m_top - 1;
// return m_stack[temp];
//}
//返回值类型
T current() {
if (!m_top)
assert(false);
int temp = m_top - 1;
return m_stack[temp];
}
bool isEmpty() {
return m_top == 0:true, false;
}
bool isFull() {
return m_top >= m_size:true, false;
}
};