前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >栈类模板(模板+DS)C++

栈类模板(模板+DS)C++

作者头像
叶茂林
发布2023-07-30 10:36:56
1280
发布2023-07-30 10:36:56
举报
文章被收录于专栏:叶子的开发者社区

题目描述

借助函数模板实现栈的操作。

栈是一种先进后出的数据结构,它的插入、删除只能在栈顶位置进行。Push为入栈操作,即插入,Pop为出栈操作,即删除。

栈的操作类似叠盘子,先放的盘子在底下,后放的盘子上面。当要取盘子,就从最上面取。

例如入栈数据1到2再到3,那么3在最上面,1在最下面。当要出栈数据,就是3先出,接着是2,最后是1出栈。

要求你自行定义栈结构,并利用函数模板以及类模板完成对char,int和float型数据的处理。其中,我们定义:

输入

第一行为测试数据数

对于每组测试数据,第一行为数据类型,第二行为操作数

对于每次操作均进行Push或Pop操作。要注意,当空栈弾栈时要给出Error提示

输出

对于每次入栈,不需输出。对于每次出栈,输出出栈元素或给出Error提示。当完成所有操作后,依次逆序输出栈中剩余元素

输入样例1

3 I 6 Push 6 Push 1 Push 1 Pop Pop Pop C 4 Pop Push a Push a Pop F 8 Push 4.1 Push 4.2 Push 14.1 Push 4.2 Push 1314 Push 1314 Pop Pop

输出样例1

1 is popped from stack! 1 is popped from stack! 6 is popped from stack! Empty Stack! Error! a is popped from stack! a  1314 is popped from stack! 1314 is popped from stack! 4.2 14.1 4.2 4.1 

思路分析

用计算机系统1LC-3的知识,用top作为指针偏移量来压栈弹栈。

整个压栈和弹栈的过程通过top偏移量和栈底指针data相加来操作。

然后空栈和满栈的判断也通过比较top和栈的长度来实现。

然后压栈的时候判断栈是否是满栈,弹栈的时候判断栈是否是空栈。

需要注意的就是top的值,top为0的时候应该是第一个进栈的,top为n-1的时候应该是最后一个进栈的,这些在判断栈是否为空和栈是否满了的时候要特别小心。

AC代码

代码语言:javascript
复制
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
using namespace std;
template<class kind>
class stack {
		kind p[10000];
		int top = -1;
	public:
		void push() {
			kind num;
			cin >> num;
			p[++top] = num;
		}
		void pop() {
			if (empty()) {
				cout << "Error!" << endl;
			} else {
				cout << p[top--] << " is popped from stack!" << endl;
			}
		}
		bool empty() {
			if (top < 0)
				return 1;
			return 0;
		}
		void display() {
			if (empty())
				cout << "Empty Stack!" << endl;
			else {
				for (int i = top;i>=0;i--)
					cout << p[i] << ' ';
				cout << endl;
			}
		}
};
int main() {
	int test, count;
	char code;
	string index;
	cin >> test;
	while (test--) {
		cin >> code >> count;
		if (code == 'I') {
			stack<int> temp;
			while (count--) {
				cin >> index;
				if (index == "Push")
					temp.push();
				else
					temp.pop();
			}
			temp.display();
		} else if (code == 'C') {
			stack<char> temp;
			while (count--) {
				cin >> index;
				if (index == "Push")
					temp.push();
				else
					temp.pop();
			}
			temp.display();
		} else {
			stack<float> temp;
			while (count--) {
				cin >> index;
				if (index == "Push")
					temp.push();
				else
					temp.pop();
			}
			temp.display();
		}
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路分析
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档