栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构:实验链栈的实现与入栈,出栈,查看栈顶元素,判断栈是否为空等基本操作的实现(c/c++版)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构:实验链栈的实现与入栈,出栈,查看栈顶元素,判断栈是否为空等基本操作的实现(c/c++版)

一. 头文件
#include
using namespace std;
#define OK 1
#define ERROR 0
typedef int numbre;   //元素类型
typedef int status;    //返回状态
typedef struct slnode    //链栈节点
{
	numbre data;        //数据部
	struct slnode* next;  //指针
}slnode,*slist; 
二. 主函数
int main()
{
	slist S;
	if (initstack(S) == OK)
		cout << "栈创建成功!" << endl;
	else cout << "栈创建失败!" << endl;
	menu();
	while (1)
	{
		cout << "请输入选项:";
		int c;
		cin >> c;
		if (c == 1)
		{
			if (input(S) == ERROR)
				cout << "进栈错误!" << endl;
			else
				cout << "进栈成功!" << endl;
		}
		else if (c == 2)
		{
			if (deletestack(S) == OK)
				cout << "已出栈" << endl;
			else
				cout << "出栈失败!" << endl;
		}
		else if (c == 3)
			cout << "当前栈顶元素为:" << gettop(S) << endl;
		else if (c == 4)
		{
			if (judgment(S) == OK) cout << "栈为空!" << endl;
			else
				cout << "栈不为空!" << endl;
		}
		else
			cout << "选项错误!" << endl;
	}
	
	return 0;
}
主函数中就是对函数的调用,详情信息请看实现函数。

这是主函数中对栈进行处理的菜单

void menu()
{
	cout << "****************************菜单************************" << endl;
	cout << "*  1.入栈   2.出栈   3.读取栈顶元素  4.判断栈是否为空  *" << endl;
	cout << "********************************************************" << endl;
}
三.实现函数 (1)初始化
status initstack(slist& S)
{
	S = NULL;
	return OK;
}

链栈并没有头节点,所以S直接为空

(2)入栈
status input(slist& S)
{
	int n;
	cout << "请输入元素个数:";
	cin >> n;
	slnode* p;
	cout << "请输入元素:";
	for (int i = 0; i < n; i++)
	{
		p = new slnode;  //
		cin >> p->data;
		p->next = S;   //
		S = p;         //
	}
	return OK;
}

建立节点p,将p分配空间,输入p的元素,让p指向第一个S,让p变为S,从而循环进行输入。

(3)出栈
status deletestack(slist& S)
{
	slnode* p = new slnode;
	if (S == NULL) return ERROR;
	cout << S->data;
	p = S;
	S = S->next;
	delete p;
	return OK;
}

输出此时S的值,也就是当前的栈顶元素。让p赋为s,S指向下一个。

(4)获取栈顶元素
numbre gettop(slist S)
{
	if (S != NULL)
		return S->data;
	return ERROR;
}

判断是否为空,不为空输出值,不改变链栈,不用加&

(5)判断是否为空栈
status judgment(slist S)
{
	if (S == NULL) return OK;
	return ERROR;
}

本篇文章为一次实验报告要求的内容,已经进行了运行测试。本人正在学习如果有什么问题欢迎讨论斧正。(希望老师如果看到,能了解我的实验并不是在网上抄的啊)
F_NCIAE_A231_2022/3/16

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768270.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号