i3geek.com
闫庚哲的个人博客

链式栈

typedef Stack_entry Node_entry;//使存储在栈中的元素和结点具有相同的类型

class Stack{
public:
	Stack();
	Stack(const Stack &original)//复制构造函数
	~Stack();
	void operator= (const Stack &original);//运算符重载
	bool empty() const;
	Error_code push(const Stack_entry &item);
	Error_code pop();
	Error_code top(Stack_entry &item) const;
protected:
	Node *top_node;
};

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;
}

Error_code Stack::pop()
{
	Node *old_top = top_node;
	if(top_node == NULL) return underflow;
	top_node=old_top->next;
	delete old_top;
	return success;
}

Stack::~Stack()
{
	while(!empty())
		pop();
}

void Stack::operator= (const Stack &original)
{
	Node *new_top,*new_copye,*original_node=original,top_node;
	if(original_node==NULL) new_top=NULL;
	else {
		now_copy=new_top=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;
		}
	}
	while(!empty())
		pop();
	top_node=new_top;
}

Stack::Stack(const Stack &original)
{
	Node * new_copy, *original_node = original.top_node;
	if(original_node == NULL) top_node =NULL;
	else {
		top_node=new_copy=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;
		}
	}
}

 

赞(0)
未经允许不得转载:爱上极客 » 链式栈
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址