利用C++实现栈的表示和操作,插入、删除、遍历等(顺序表示)

一、创建sqstack.h头文件,定义栈并声明基本操作函数

#pragma once
#include<iostream>
using namespace std;

#define MAXSIZE 100 //可能达到的最大空间

//定义栈
struct SqStack
{
	int* base; //栈底指针
	int* top; //栈顶指针
	int stacksize; //栈可用最大容量
};

//初始化
bool InitStack(SqStack& S);

//插入  入栈
bool Push(SqStack& S, int e);

//删除
bool Pop(SqStack& S, int& e);

//遍历
void PrintSqStack(SqStack S);

//判断是否为空
bool StackEmpty(SqStack S);

//栈长度
int StackLength(SqStack S);

//清空
bool ClearStack(SqStack& S);

//销毁
bool DestoryStack(SqStack& S);

二、创建sqstack.cpp源文件,将声明的基本操作具体实现

#include"sqstack.h"

//初始化
bool InitStack(SqStack& S)
{
	S.base = new int[MAXSIZE]; //分配空间,base指向数组首地址  栈底
	if (!S.base)
	{
		exit(0); //分配失败退出系统
	}
	S.top = S.base; //栈顶指针等于栈底指针  初始化为空表
	S.stacksize = MAXSIZE; //最大容量
	return true;
}

//插入  入栈
bool Push(SqStack& S, int e)
{
	if (S.top - S.base == S.stacksize) //判断栈是否已满
	{
		return false;
	}
	*S.top++ = e; //给*top赋值,并让top指针指向下一空间
	return true;
}

//删除
bool Pop(SqStack& S, int& e)
{
	if (S.top == S.base) //判断栈是否为空
	{
		return false;
	}
	e = *--S.top; //先栈顶下移,再将值解引用赋值给e
	return true;
}

//遍历
void PrintSqStack(SqStack S)
{
	while (S.top != S.base)
	{
		S.top--;
		cout << *S.top << endl;
	}
}

//判断是否为空
bool StackEmpty(SqStack S)
{
	if (S.top == S.base)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//栈长度
int StackLength(SqStack S)
{
	return S.top - S.base;
}

//清空
bool ClearStack(SqStack& S)
{
	if (S.base)
	{
		S.top = S.base;
		return true;
	}
}

//销毁
bool DestoryStack(SqStack& S)
{
	if (S.base)
	{
		delete S.base;
		S.stacksize = 0;
		S.base = S.top = NULL;
	}
	return true;
}

三、在主函数中测试

#include<iostream>
using namespace std;
#include"sqstack.h" //包含头文件


int main()
{
	//1.创建栈S,并初始化
	SqStack S;
	InitStack(S);

	//2.插入元素
	int arr[5] = { 5,4,3,2,1 };
	for (int i = 0; i < 5; i++)
	{
		Push(S, arr[i]);
	}
	cout << "插入后打印:" << endl;
	//3.遍历
	PrintSqStack(S);

	//4.删除
	int e;
	Pop(S, e);
	cout << "元素" << e << "已删除" << endl;
	cout << "删除后打印:" << endl;
	PrintSqStack(S);

	//5.判断是否为空
	if (StackEmpty(S))
	{
		cout << "栈为空" << endl;
	}
	else
	{
		//6.栈的元素个数
		cout << "栈不为空元素个数为:" << StackLength(S) << endl;
	}

	//7.清空
	ClearStack(S);
	cout << "清空后打印:" << endl;
	PrintSqStack(S);

	//8.销毁
    DestoryStack(S);
	system("pause");
	return 0;
}

四、最终效果

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值