用java或者C++实现一个堆栈类

//用java或者C++实现一个堆栈类,并考虑异常

实现思想:用链表实现的一个栈的操作,可以跟据栈的元素个数动态分配内存
尚未在vc环境下调试,算是伪码吧

Struct Node
{
	int entry;
	int *next;
	Node();
	Node(int item, Node *add_on = NULL);
};

Node::Node()
{
	next = NULL;
}

Node::Node(int item, Node *add_on)
{
	entry = item;
	next = add_on;
}

Class Stack
{
	public:
		Stack();
		Stack(Node &item);
		~Stack();
		Error_code push(int item);
		Error_code pop();
		Error_code top(int &item);
		bool empty();
	private:
		Node *topNode;
};

Stack::Stack()
{
	topNode = NULL;
}

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

//简单的单向链表,每次新建一个元素都链到栈顶
Stack::Stack(Node &item)
{
	Node *oriangle = item.topNode;
	Node *newTop;
	Node *newCopy;
	
	if(!oriangle)
	{
		return;
	}
	else
	{
		newCopy = new Node(oriangle->entry);
		newTop = newCopy;
		oriangle = oriangle->next;
		
		while(oriangle)
		{
			newCopy->next = new Node(oriangle->entry);
			newCopy = newCopy->next;
			oriangle = oriangle->next;
		}
	}
	topNode = newTop;
}

//把item 挂到最新的topNode下面
Error_code Stack::push(int item)
{
	Node *newNode;
	newNode = newNode(item, topNode);
	if (!newNode)
	{
		return overflow;
	}
	topNode = newNode;
	return success;
}

//每次都取栈顶
Error_code Stack::pop()
{
	Node *oldNode = topNode;
	if (!topNode)
	{
		return underflow;
	}
	
	topNode = topNode->next;
	delete oldNode;
	return success;
}

//当前的topNode 为空,则为空
bool Stack::empty()
{
	return topNode == NULL;
}

Error_code top(int &item)
{
	if (!topNode)
	{
		return underflow;
	}
	
	item = topNode->entry;
	return success;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值