Stack(2)Stack的链式实现

stack.h


/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 
#ifndef QUEUE_H
#define QUEUE_H
#include "utility.h"

typedef int ElemType;

class LinkStack
{
public:
	LinkStack():count_(0),top_node_(NULL){}
	~LinkStack();

	bool Empty() const  //内联
	{
		return count_ == 0;
	}

	size_t Size() const     //内联
	{
		return count_;
	}

	bool Top(ElemType &entry) const;
	void Push(const ElemType &entry);  //记得count++
	bool Pop();    //记得count--,并释放空间


	void ShowALLEntry() const;

private:
	struct Node
	{
		ElemType entry_;
    	Node *next_;
		Node(const ElemType &entry,Node *next):entry_(entry),next_(next){}
	};

	DISALLOW_COPY_AND_ASSIGN(Queue);   //在utility.h中定义,为了禁用拷贝和赋值构造函数

	size_t count_;
	Node *top_node_;
};

#endif

stack.cpp

/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#include "stdafx.h"
#include "utility.h"
#include "stack.h"
#include <iostream>
using namespace std;

LinkStack::~LinkStack()
{
	while (!Empty())
	{
		Pop();
	}
}



bool LinkStack::Top(ElemType &entry) const
{
	if (Empty())
		return false;

	entry=top_node_->entry_;
	return true;
}

void LinkStack::Push(const ElemType &entry)
{
	Node *new_node=new Node(entry,top_node_);
	top_node_=new_node;
	count_++;    //不要忘了
}

bool LinkStack::Pop()
{
	if (Empty())
		return false;

	Node *next_node=top_node_->next_;
	delete top_node_;
	top_node_=next_node;

	count_--;   //不要忘了
	return true;
}


void LinkStack::ShowALLEntry() const
{
	Node *tmp_node=top_node_;

	while (tmp_node != NULL)
	{
		cout<<tmp_node->entry_<<' ';
		tmp_node = tmp_node->next_;
	}

	cout<<endl;
}

utility.h


/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#ifndef UTILITY_H
#define UTILITY_H
#include <cstddef>
#include <cstdlib>

#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
  TypeName(const TypeName&);               \
  void operator=(const TypeName&)

#endif

main.cpp


/*----------------------------------------------- 
Created By EverSteins 
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/ 

#include "stdafx.h"
#include "stack.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	LinkStack s1;

	
	s1.Push(1);
	s1.Push(2);
	s1.Push(3);
	
	s1.ShowALLEntry();

	s1.Pop();
	s1.Pop();
	s1.Pop();
	s1.Pop();

	cin.get();
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值