#include <iostream>
using namespace std;
const unsigned int maxn = 65535;
template<typename T>
class myStack
{
public:
myStack(): length(0)
{
head = bottom = &data[0];
memset(data, 0, sizeof(data));
}
void push(const T&);
void pop();
T& top();
bool empty()
{
return length == 0;
}
unsigned int size()
{
return length;
}
private:
T data[maxn];
int *bottom, *head;
unsigned int length;
};
template<typename T>
void myStack<T>::push(const T& val)
{
if(empty())
{
*bottom = *head = val;
}
else
{
*++head = val;
}
length++;
}
template<typename T>
T& myStack<T>::top()
{
return *head;
}
template<typename T>
void myStack<T>::pop()
{
if(empty())
{
cout << "empty" << endl;
return;
}
else
{
head--;
}
length--;
}
int main(void)
{
myStack<int> st;
for(int i = 1; i <= 10; ++i)
{
st.push(i);
}
cout << "size: " << st.size() << endl;
for(int j = 0; j < 10; ++j)
{
if(!st.empty())
{
cout << st.top() << endl;
st.pop();
cout << "size: " << st.size() << endl;
}
}
return 0;
}
栈C++模版实现(数组版)
最新推荐文章于 2022-11-25 10:44:50 发布