El establecimiento y funcionamiento básico de la pila secuencial.

Introducción a la operación:
1. Empuje un elemento
en la pila 2. Saque un elemento
3.
Saque la secuencia de la pila 4. Obtenga el elemento superior de la pila
5. Determine si la pila está vacía o llena
6. Calcule el tamaño actual de la pila
7. Salir del sistema operativo

#include<windows.h>
#include<iostream>
using namespace std;
typedef struct
{
    
    
	int ST[101];
	int top = 0;
}stack;   //顺序栈的类型定义
 //输出栈内元素
void putstack(stack S)
{
    
    
	if (S.top == 0)cout << "栈为空!";
	else
	{
    
    
		cout << "出栈时的顺序为:";
		for (; S.top > 0; S.top--)
		{
    
    
			cout << S.ST[S.top] << " ";
		}
	}
	cout << endl;
}
//判断栈空还是栈满
void Judge(stack S, int m)
{
    
    
	if (S.top == m)
	{
    
    
		cout << "栈满";
		cout << endl;
	}
	else if (S.top == 0)
		cout << "栈空" << endl;
	else cout << "栈非空且不满栈" << endl;
}
//入栈一个元素
stack Enstack(stack S, int m)
{
    
    
	if (S.top == m)
	{
    
    
		cout << "栈满,无法完成入栈操作";
		cout << endl;
	}
	else
	{
    
    
		int x;
		cout << "请输入入栈元素:";
		cin >> x;
		S.ST[++S.top] = x;
		cout << endl;
	}
	return S;
}
//出栈一个元素
stack Destack(stack S)
{
    
    
	if (S.top == 0)cout << "栈空,无法完成出栈操作!";
	else
	{
    
    
		S.top--;
	}
	return S;
}
//获取栈顶元素
void Gettopstack(stack S)
{
    
    
	if (S.top == 0)cout << "栈空,无法完成获取栈顶元素操作!";
	else
	{
    
    
		cout << "栈顶元素为:" << S.ST[S.top];
	}
	cout << endl;
}
//计算当前栈的大小
void Count_Size(stack S)
{
    
    
	int num = 0;
	if (S.top == 0)cout << "当前栈为空";
	else
	{
    
    
		for (; S.top > 0; S.top--)
		{
    
    
			num++;
		}
		cout << "当前栈的大小为:" << num << endl;
	}
}
int main()
{
    
    
	int m, w;
	stack S;
	cout << "当前操作为栈内数据初始化,请输入栈的元素个数:";
	cin >> m;
	cout << "请输入栈内元素值:";
	for (int i = 0; i < m; i++)
	{
    
    
		S.top++;
		cin >> S.ST[S.top];
	}
	while (1)
	{
    
    
		Sleep(1000);
		cout << "**********操作介绍***********" << endl;
		cout << "       1、入栈一个元素        " << endl;
		cout << "       2、出栈一个元素        " << endl;
		cout << "       3、输出出栈顺序        " << endl;
		cout << "       4、获取栈顶元素        " << endl;
		cout << "       5、判断栈空还是栈满    " << endl;
		cout << "       6、计算当前栈的大小    " << endl;
		cout << "       7、退出操作系统        " << endl;
		cout << "*****************************" << endl;
		cout << "请输入你的操作代号:";
		cin >> w;
		switch (w)
		{
    
    
		case 1:
			S = Enstack(S, m);
			break;
		case 2:
			S = Destack(S);
			break;
		case 3:
			putstack(S);
			break;
		case 4:
			Gettopstack(S);
			break;
		case 5:
			Judge(S, m);
			break;
		case 6:
			Count_Size(S);
			break;
		}
		if (w == 7)break;
	}
	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/gets_s/article/details/105151115
Recomendado
Clasificación