堆栈——数组实现

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime> 

using namespace std;

using ElemType = int;
const int MAXSIZE = 20;

// 堆栈结构
class Stack {
public:
	ElemType data[MAXSIZE];
	int top; 
};

// 初始化堆栈 
void initStack(Stack &stack, int n)
{
	stack.top = -1;
	srand(time(NULL));
	while (n--) {
		stack.top++;
		stack.data[stack.top] = rand()%100 + 1;
	}
}

// 判空 
bool isEmpty(const Stack &stack)
{
	if (stack.top == -1)
		return true;
	return false;
}

// 压栈 
void push(Stack &stack, ElemType val)
{
	if (stack.top == MAXSIZE - 1) {
		cout << "stack is full...\n";
		return;
	}
	stack.top++;
	stack.data[stack.top] = val;
}

// 出栈 
void pop(Stack &stack)
{
	if (isEmpty(stack)) {
		cout << "stack is empty...\n";
		return;
	}
	stack.top--;
}

// 返回栈顶元素 
const ElemType& getTop(const Stack &stack)
{
	if (isEmpty(stack)) {
		cout << "stack is empty...\n";
	}
	return stack.data[stack.top];
}

// 打印 
void print(const Stack &stack)
{
	if (isEmpty(stack)) {
		cout << "Empty stack...\n";
	}
	int n = stack.top;
	cout << "从栈顶到栈底的元素依次为:";
	while (n != -1) {
		cout << stack.data[n--] << " ";
	}
	cout << endl;
}

int main()
{
	Stack stack;
	initStack(stack, 10); 
	print(stack);
	pop(stack);
	print(stack);
	push(stack, 100);
	print(stack);
	cout << "栈顶元素为:" << getTop(stack) << endl;
}

  

转载于:https://www.cnblogs.com/xzxl/p/8643119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值