数据结构6-顺序栈

该文章展示了如何使用C++编程语言实现一个顺序栈的数据结构,包括构造、析构、入栈、出栈、取栈顶元素以及判断栈空等基本操作。代码中使用了模板类,可以适用于不同类型的元素。同时,文章还提供了一个简单的交互式菜单来演示这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;
const int MAXSIZE = 100;
struct People
{
	int id;
	string name;
	int age;
};

/*实现顺序栈的构造,析构,入栈,出栈,
取栈顶元素,判断栈空,菜单*/
template <class Element>
class SeqStack
{
public:
	SeqStack();
	~SeqStack() {};
	void push(Element x);
	Element pop();
	Element getTop();
	bool ifEmpty();
	void menu();

private:
	Element SStack[MAXSIZE];
	int top;
};
template <class Element>
SeqStack<Element>::SeqStack()
{
	top = -1;
}
template <class Element>
void SeqStack<Element>::push(Element x)
{
	if (top == MAXSIZE - 1) throw"上溢";
	SStack[++top] = x;
}
template <class Element>
Element SeqStack<Element>::pop()
{
	if (top == -1)throw "下溢";
	Element x = SStack[top--];
	return x;
}
template <class Element>
Element SeqStack<Element>::getTop()
{
	if (top == -1)throw "栈为空";
	return SStack[top];
	
}
template <class Element>
bool SeqStack<Element>::ifEmpty()
{
	if (top == -1)return 1;
	else return 0;
}

template <class Element>
void SeqStack<Element>::menu()
{
	int choice=0;
	int pId = 0;
	string pName;
	int pAge = 0;
	int pos = 0;
	People p1 = { pId, pName, pAge };
	Element x;
	
	/*实现顺序栈的构造,析构,入栈,出栈,
	取栈顶元素,判断栈空,菜单*/
	cout <<"-----菜单-----"<< endl;
	cout <<"1.取栈顶元素\t2.判断是否为空"<< endl;
	cout <<"3.入栈\t4.出栈"<< endl;
	cout <<"请输入你要实现的操作:";
	cin >> choice;
	cout << endl;
	switch (choice)
	{
	case 1:
		x = getTop();
		cout<<"栈顶元素为:"<<x.id<<" "<<x.name<<" "<<x.age<<endl;
		break;
	case 2:
		if (ifEmpty())
		{
			cout << "此栈为空" << endl;
		}
		else
		{
			cout << "此栈非空" << endl;
		}
		break;
	case 3:
		pId=0; 
		pAge=0;
		pos=0;
		
		cout << "请输入你要入栈的人物的id:";
		cin >> pId;
		cout << endl;
		cout << "请输入你要入栈的人物的name:";
		cin >> pName;
		cout << endl;
		cout << "请输入你要入栈的人物的age:";
		cin >> pAge;
		cout << endl;
		p1={ pId, pName, pAge };
		push(p1);
		cout << endl;
		break;
	case 4:
		x = pop();
		cout << "出栈元素为:" << x.id << " " <<x.name << " " << x.age << endl;
		break;
	default:
		cout << "你输入的数字有误,请重新输入" << endl;
		break;
	}

}
int main()
{
	SeqStack<People> s1;
	while (1)
	{
		s1.menu();
	}



	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值