stack.cpp

来自「数据结构与程序设计教材源码 数据结构与程序设计教材源码」· C++ 代码 · 共 106 行

CPP
106
字号
 
template <class Stack_entry>
Error_code Stack<Stack_entry>::push(const Stack_entry &item)
{
   Stack_node<Stack_entry> *new_top = new Stack_node<Stack_entry>(item, top_node);
   if (new_top == NULL) return fail;
   top_node = new_top;
   return success;
}
 
template <class Stack_entry>
Stack<Stack_entry>::~Stack()
{
   while (!empty())
      pop();
}
 
template <class Stack_entry>
Stack_node<Stack_entry>::Stack_node()
{
   next = NULL;
}
 
template <class Stack_entry>
Stack<Stack_entry>::Stack()
{
   top_node = NULL;
}
 
template <class Stack_entry>
Stack_node<Stack_entry>::
   Stack_node (Stack_entry item, Stack_node<Stack_entry> *add_on = NULL )
   {
      entry = item;
      next = add_on;
   }
 
template <class Stack_entry>
Stack<Stack_entry>::Stack (const Stack<Stack_entry> &copy)
{
   Stack_node<Stack_entry> *new_copy, *copy_node = copy.top_node;
   if (copy_node == NULL) top_node = NULL;
   else {
      new_copy = top_node = new Stack_node<Stack_entry>(copy_node->entry);
      while (copy_node->next != NULL) {
         copy_node = copy_node->next;
         new_copy->next = new Stack_node<Stack_entry>(copy_node->entry);
         new_copy = new_copy->next;
      }
   }
}
 
template <class Stack_entry>
void Stack<Stack_entry>:: operator =(const Stack<Stack_entry> &copy)
{
   Stack_node<Stack_entry> *new_top, *new_copy, *copy_node = copy.top_node;
   if (copy_node == NULL) new_top = NULL;
   else {
      new_copy = new_top = new Stack_node<Stack_entry>(copy_node->entry);
      while (copy_node->next != NULL) {
         copy_node = copy_node->next;
         new_copy->next = new Stack_node<Stack_entry>(copy_node->entry);
         new_copy = new_copy->next;
      }
   }
   Stack_entry temp;
   while (!empty()) pop();
   top_node = new_top;
}
 
template <class Stack_entry>
bool Stack<Stack_entry>::empty() const
/*   
Post: Return true if the Stack is empty,
otherwise return false.
 */
{
   return top_node == NULL;
}
 
template <class Stack_entry>
Error_code Stack<Stack_entry>::top(Stack_entry &item) const
/*   
Post: The top of the Stack is reported in item. If the Stack 
is empty return underflow otherwise return success.
 */
{
   if (top_node == NULL) return underflow;
   item = top_node->entry;
   return success;
}
 
template <class Stack_entry>
Error_code Stack<Stack_entry>::pop()
/*   
Post: The top of the Stack is removed.  If the Stack 
is empty return underflow otherwise return success.
 */
{
   Stack_node<Stack_entry> *old_top = top_node;
   if (top_node == NULL) return underflow;
   top_node = old_top->next;
   delete old_top;
   return success;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?