template<class T> class Stack{
friend ostream& operator<< <T> (ostream &, Stack<T>&);
public:
Stack(int count = 9):top(-1),maxcount(count)
{
data = new T[maxcount]();
}
Stack(const Stack& rhs):top(rhs.top),maxcount(rhs.maxcount)
{
data = new T[maxcount]();
memcpy(data,rhs.data,sizeof(T)*maxcount);
}
Stack& operator=(const Stack& rhs)
{
if (this == &rhs)
{
return *this;
}
top = rhs.top;
maxcount = rhs.maxcount;
delete []data;
data = new T[maxcount]();
memcpy(data, rhs.data, sizeof(T)*maxcount);
return *this;
}
~Stack()
{
delete []data;
}
T& Top() const;
void Push(const T&);
void Pop();
size_t Size() const;
inline bool Empty() const;
inline bool Full() const;
private:
T* data;
int top;
int maxcount;
};
template<class T> T& Stack<T>::Top() const
{
if (Empty())
{
exit(1);
}
return data[top];
}
template<class T> void Stack<T>::Push(const T& val)
{
if (Full())
{
return;
}
data[++top] = val;
}
template<class T> void Stack<T>::Pop()
{
if (Empty())
{
return;
}
--top;
}
template<class T> size_t Stack<T>::Size() const
{
return top+1;
}
template<class T> bool Stack<T>::Empty() const
{
return top == -1;
}
template<class T> bool Stack<T>::Full() const
{
return (top+1) == maxcount;
}
template<class T> ostream& operator<<(ostream &os, Stack<T>& s)
{
if (!s.Empty())
{
for (int i = 0; i <= s.top; ++i)
{
os<<s.data[i]<<' ';
}
}
return os;
}
棧(數組形式)實現_c++
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.