📄 stack.h
字号:
enum Error_code{ underflow,overflow,success};
template<class T>
class Stack{
public:
// Standard Stack methods
Stack();
bool empty() const;
Error_code push(const T &item);
Error_code pop();
Error_code top(T &item)const;
//safety features linked structures
~Stack();
Stack(const Stack<T> & original);
void operator=(const Stack<T> & original);
protected:
Node<T> *top_node;
};
template<class T>
Stack<T>::Stack()
{
top_node=NULL;
}
template<class T>
Error_code Stack<T>::push(const T & item)
/*Post:T item is added to the top of the stack;returns success or returns a code of
overflow if dynamic memory is exhausted.*/
{
Node<T> *new_top=new Node<T>(item,top_node);
if(new_top==NULL) return overflow;
top_node=new_top;
return success;
}
template<class T>
bool Stack<T>::empty()const
/*Pre:None
Post:If the Stack is empty,true is returned.Otherwise false is returned.*/
{
return top_node==NULL;
}
template<class T>
Error_code Stack<T>::pop()
/*Pre: The top of the stack is removed. if the stack is empty the method returns underflow;
otherwise it return success.*/
{
Node<T> *old_node=top_node;
if(top_node==NULL) return underflow;
top_node=old_node->next;
delete old_node;
return success;
}
template<class T>
Error_code Stack<T>::top(T & item)const
/*Pre: None.
Post: If the stack is not empty, the top of the stack is returned in item. If the
Stack is empty an Error_code of underflow is returned.*/
{
if(top_node==NULL) return underflow;
item=top_node->entry;
return success;
}
template<class T>
Stack<T>::~Stack() //Destructor
/*Post: The stack is cleared.*/
{
while(!empty()) pop();
}
template<class T>
void Stack<T>::operator=(const Stack<T> & original) //Overload assignment
/*Post: The stack is reset as a cop of Stack original.*/
{
Node<T> *new_top,*new_copy,*original_node=original.top_node;
if(original_node==NULL) new_top=NULL;
else //Duplicate the linked nodes
{
new_copy=new_top=new Node<T>(original_node->entry);
while(original_node->next!=NULL){
original_node=original_node->next;
new_copy->next=new Node<T>(original_node->entry);
new_copy=new_copy->next;
}
}
while(!empty()) //Clean out old Stack entries
pop();
top_node=new_top; //and replace thme with new entries.
}
template<class T>
Stack<T>::Stack(const Stack<T> & original) //constructor
/*Post: The stack is initialized as a copy of Stack original.*/
{
Node<T> *new_copy,*original_node=original.top_node;
if(original_node==NULL) top_node=NULL;
else //Duplicate the linked nodes
{
top_node=new_copy=new Node<T>(original_node->entry);
while(original_node->next!=NULL){
original_node=original_node->next;
new_copy->next=new Node<T>(original_node->entry);
new_copy=new_copy->next;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -