码迷,mamicode.com
首页 > 编程语言 > 详细

堆栈——数组实现

时间:2018-03-25 11:55:03      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:srand   data   cpp   amp   gpo   tac   lib   pre   als   

#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;
}

  

堆栈——数组实现

标签:srand   data   cpp   amp   gpo   tac   lib   pre   als   

原文地址:https://www.cnblogs.com/xzxl/p/8643119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!