为了让学习数据结构与算法的同学更好地理解栈,这里写出了栈的C++实现(顺序存储)如果想要链式存储,还请看本专栏下一篇文章。
#pragma once
#define MAX_SIZE 100
template <typename T>
class SequenceStack {
private:
typedef struct{
int top;
T data[MAX_SIZE];
}SqStack;
SqStack m_Stack;
public:
SequenceStack();
public:
bool push(T nValue);
bool pop(T* result);
bool clear();
bool IsEmpty();
bool getSize();
};
template<typename T>
inline SequenceStack<T>::SequenceStack()
{
m_Stack. top = -1;
}
template<typename T>
inline bool SequenceStack<T>::push(T nValue)
{
if (m_Stack.top == MAX_SIZE - 1) {
return false;
}
else {
m_Stack.top++;
m_Stack.data[m_Stack.top] = nValue;
}
return true;
}
template<typename T>
inline bool SequenceStack<T>::pop(T * result)
{
if (m_Stack.top == -1) {
return false;
}
*result = m_Stack.data[m_Stack.top];
m_Stack.top--;
return true;
}
template<typename T>
inline bool SequenceStack<T>::clear()
{
m_Stack.top = -1;
return true;
}
template<typename T>
inline bool SequenceStack<T>::IsEmpty()
{
if (m_Stack.top == -1) {
return false;
}
else{
return true;
}
}
template<typename T>
inline bool SequenceStack<T>::getSize()
{
return m_Stack.top + 1;
}
这里只是为了更好的理解栈的先入后出,如果大家发现什么问题,还请大家及时指出来,大家共同进步!!!