首页 > 其他 > 详细

链接栈

时间:2016-12-11 02:33:32      阅读:139      评论:0      收藏:0      [点我收藏+]
#include <iostream>
using namespace std;
typedef int stackEntry;

const int overflow = 1;
const int underflow = 2;
const int success = 0;

struct Node
{
	stackEntry data;
	Node *next;
};

class stack
{
public:
	stack();
	bool empty() const;
	int push(const stackEntry &item);
	int pop();
	int top(stackEntry &item) const;
//	void operator = (const stack &original);
//	stack(const stack &original);
protected:
	Node *top_node;
};

stack::stack()
{
	top_node = NULL;
}

int stack::push(const stackEntry &item)
{
	Node *new_top = new Node;

	//为元素item构建新的节点,该节点指向原来的栈顶元素
	if (new_top == NULL)
		return overflow;
	new_top->data = item;
	new_top->next = top_node;
	top_node = new_top;
	return success;
}

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

int stack::top(stackEntry &item) const
{
	if (top_node == NULL)
		return underflow;
	item = top_node->data;
	return success;
}

bool stack::empty() const
{
	if (top_node != NULL)
		return false;
	return true;
}

int main()//乘客上下飞机模拟程序
{
	int n;
	int item;
	stack passengers;
	stack temp;
	cout << "输入乘客人数n" << endl;
	cin >> n;
	cout << "按登机顺序输入乘客编号" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> item;
		temp.push(item);
	}
	passengers = temp;
	cout << endl << endl;
	cout << "乘客下机顺序是:";
	while (!passengers.empty())
	{
		passengers.top(item);
		cout << item << " ";
		passengers.pop();
	}
	cout << endl;
}

  

链接栈

原文:http://www.cnblogs.com/changed/p/6158751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!