简简单单的栈实现,考试可能会考?
作者:
小小蒟蒻
,
2020-11-10 01:35:52
,
所有人可见
,
阅读 487
#pragma once
#include <iostream>
#include <string.h>
const int DEFAULT_SIZE = 4;
template <typename T>
class CStack {
public:
CStack(T* pData = nullptr, int nCount = 0, int nSize = DEFAULT_SIZE)
: m_pData(pData), m_nCount(nCount), m_nSize(nSize) {
m_pData = new T[m_nSize];
if (m_pData == nullptr) return;
std::cout << "创建动态栈" << std::endl;
}
~CStack() {
if (m_pData != nullptr) delete[]m_pData;
m_nCount = m_nSize = 0;
std::cout << "销毁动态栈" << std::endl;
}
void Resize(int nCount) {
if (nCount <= 0) return;
if (nCount >= m_nSize) m_nSize = nCount + (nCount >> 1);
else if (4 * nCount < m_nSize)
nCount < DEFAULT_SIZE ? m_nSize = DEFAULT_SIZE : m_nSize >>= 1;
T* pData = new T[m_nSize];
if (pData == nullptr) return;
memcpy_s(pData, m_nSize * sizeof(T), m_pData, nCount * sizeof(T));
delete[]m_pData;
m_pData = pData;
}
void Push(const T& data) {
Resize(m_nCount + 1);
m_pData[m_nCount++] = data;
}
void Pop() {
if (m_nCount >= 1)
Resize(m_nCount--);
}
T& operator[](int r) const { return m_pData[r]; }
void travel() const {
std::cout << "栈的大小为" << m_nSize << std::endl;
std::cout << "栈中保存的元素个数为" << m_nCount << std::endl;
for (int i = 0; i < m_nCount; i++)
std::cout << m_pData[i] << " ";
std::cout << std::endl;
}
const int Size() const { return m_nCount; }
private:
T* m_pData = nullptr;
int m_nCount = 0;
int m_nSize = 0;
};
#include "stack.h"
void Clear(CStack<int>& st) {
while (st.Size()) {
st.Pop();
st.travel();
}
}
int main() {
CStack<int> st;
for (int i = 0; i < 11; i++)
st.Push(i);
st.travel();
Clear(st);
return 0;
}
测试结果: