Stack.cpp
上传用户:stella1212
上传日期:2022-08-06
资源大小:567k
文件大小:2k
- #include "Stack.h"
- #include"Struct.h"
- Stack::Stack(void)
- {
- top_node = NULL;
- }
- //用于检查栈是否为空
- bool Stack::empty() const
- {
- if(top_node == NULL)
- return true;
- return false;
- }
- //将元素item 压入到栈顶,如果栈已满,则返回上溢标志overflow
- Error_code Stack::push(const Stack_entry &item)
- {
- Node *new_top = new Node(item,top_node);
- if(new_top ==NULL)
- return overflow;
- top_node = new_top;
- return success;
- }
- //将栈顶的元素弹出,如果栈为空,则返回underflow
- Error_code Stack::pop()
- {
- Node *old_node = top_node;
- if(top_node == NULL)
- return underflow;
- top_node = top_node->next;
- delete old_node;
- return success;
- }
- //得到栈顶的元素的方法,如果栈为空,那么返回下溢标志;
- Error_code Stack::top(Stack_entry &item) const
- {
- if(top_node ==NULL)
- return underflow;
- item = top_node->entry;
- return success;
- }
- //拷贝构造函数
- Stack::Stack(const Stack &original)
- {
- Node *new_copy ,*original_node;
- original_node = original.top_node;
- if(original_node == NULL)
- top_node = NULL;
- else
- {
- new_copy = top_node = new Node(original_node->entry);
- while(original_node->next != NULL)
- {
- original_node = original_node->next;
- new_copy->next = new Node(original_node ->entry);
- new_copy = new_copy->next;
- }
- }
- }
- //赋值操作符重载函数,用来避免出现赋值导致的内存消耗
- void Stack::operator =(const Stack &original)
- {
- Node* new_copy,*new_top,*original_node;
- original_node = original.top_node;
- if(original_node == NULL)
- new_top = NULL;
- else
- {
- new_top = new_copy = new Node(original_node ->entry);
- while(original_node!=NULL)
- {
- original_node = original_node->next;
- new_copy ->next = new Node(original_node->entry);
- new_copy = new_copy->next;
- }
- }
- while(!empty())
- pop();
- top_node = new_top;
- }
- //析构函数,清空栈中分配的内存
- Stack::~Stack(void)
- {
- while(!empty())
- pop();
- }