链栈实现(C++)
View Code
typedef int DataType; struct Node{ DataType entry; Node * next; Node(); Node(DataType item, Node * add_on = NULL); }; class DyStack{ public: DyStack(); bool empty() const; ErrorCode push(const DataType &item); ErrorCode pop(); ErrorCode top(DataType &item) const; ~DyStack(); DyStack(const DyStack &origin); void operator = (const DyStack &origin); protected: Node * top_node; }; Node::Node() { next = NULL; } Node::Node(DataType item, Node * add_on) { entry = item; next = add_on; } DyStack::DyStack() { top_node = NULL; } bool DyStack::empty() const { if(top_node == NULL) return true; else return false; } ErrorCode DyStack::push(const DataType &item) { ErrorCode outcome = success; Node * pNew = new Node(item, top_node); if(pNew == NULL) outcome = overflow; else top_node = pNew; return outcome; } ErrorCode DyStack::pop() { ErrorCode outcome = success; if(top_node == NULL) outcome = underflow; else { Node * p = top_node; top_node = top_node->next; delete p; } return outcome; } ErrorCode DyStack::top(DataType &item) const { ErrorCode outcome = success; if(top_node == NULL) outcome = underflow; else item = top_node->entry; return outcome; } DyStack::~DyStack() { while(!empty()) pop(); } DyStack::DyStack(const DyStack &origin) { Node *new_copy, *origin_node=origin.top_node; if(origin.top_node == NULL) top_node = NULL; else { new_copy=top_node=new Node(origin_node->entry); while(origin_node->next!=NULL) { origin_node=origin_node->next; new_copy->next=new Node(origin_node->entry); new_copy=new_copy->next; } } } void DyStack::operator=(const DyStack &origin) { Node *new_top, *new_copy, *origin_node=origin.top_node; if(origin.top_node == NULL) new_top = NULL; else { new_copy=new_top=new Node(origin_node->entry); while(origin_node->next!=NULL) { origin_node=origin_node->next; new_copy->next=new Node(origin_node->entry); new_copy=new_copy->next; } } while(!empty()) pop(); top_node=new_top; }
注意几个问题:
1、析构函数
当对象离开作用域范围时,用来释放其占用的资源。一般情况下,需要手动编写析构函数时,都要进行重载赋值运算符和拷贝构造函数。
2、重载赋值运算符
3、拷贝构造函数