码迷,mamicode.com
首页 > 其他好文 > 详细

链接栈

时间:2016-12-11 02:36:01      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:under   passenger   protect   ext   flow   ons   iostream   ++   ios   

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

  

链接栈

标签:under   passenger   protect   ext   flow   ons   iostream   ++   ios   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!