第二问:第三问编设中...
#ifndef _stack_H_
#define _stack_H_
#include <iostream.h>
#include <stdlib.h>
template <class T>
class stack
{
public:
stack(); //默认构造函数
stack(const stack<T> &); //复制构造函数
virtual ~stack(); //择构函数
void push(T storage);
void pop(T & storage);
const T pop();
const T top() const;
void makeEmpty();
inline bool isEmpty() const;
inline int length() const;
const stack<T> & operator = (const stack<T> &);
protected:
struct node
{
T data;
node *next;
node() :next(0) {}
node(const T & a) :data(a), next(0) {}
} *sp;
int size;
};
template <class T>
stack<T>::stack() :sp(0), size(0)
{}
template <class T>
stack<T>::stack(const stack<T> ©) :sp(0), size(0)
{
*this = copy;
}
template <class T>
stack<T>::~stack()
{
makeEmpty();
}
//在堆栈中增加一个元素
template <class T>
void stack<T>::push(T storage)
{
//create new data
node *newnode = new node;
newnode->next=sp;
newnode->data=storage;
sp = newnode;
++size;
}
//在堆栈中删除一个元素
template <class T>
void stack<T>::pop(T & storage)
{
if(isEmpty())
{
cerr << "\nError: accessing empty stack through method stack::pop\n";
exit(1);
}
//存储数据
storage = sp->data;
node *temp = sp;
sp = sp->next;
delete temp;
--size;
}
//在堆栈中删除一个元素,同时返回这个元素
template <class T>
const T stack<T>::pop()
{
T val;
pop(val);
return val;
}
template <class T>
const T stack<T>::top() const
{
if(isEmpty())
{
cerr << "\nError: accessing empty stack through method stack::top\n";
exit(1);
}
return sp->data;
}
//检测堆栈大小
template <class T>
int stack<T>::length() const
{
return size;
}
//把堆栈变为空
template <class T>
void stack<T>::makeEmpty()
{
node *temp;
while(sp!=0)
{
temp = sp;
sp = sp->next;
delete temp;
}
size = 0;
}
//检测堆栈是否为空
template <class T>
bool stack<T>::isEmpty() const
{
return size == 0;
}
template <class T>
const stack<T> & stack<T>::operator = (const stack<T> & copy)
{
makeEmpty();
if(copy.isEmpty())
return *this;
sp = new node(copy.sp->data);
node *newnode,*end = sp;
for(newnode = copy.sp->next; newnode; newnode = newnode->next)
{
end->next = new node(newnode->data);
end = end->next;
}
size = copy.size;
return *this;
}
#endif