数据结构(栈)的代码实现和测试

栈的实现算是非常简单的。

STL中实际上也由stack的容器,因此,重复造轮子是完全没有必要的。

实现一下栈可以帮助我们更好的理解栈的应用和结构

以下是栈的代码:

stack.h

#pragma once
#include<bits/stdc++.h>
template<typename E>class Stack //栈的顺序实现
{
private:
	void Assert(bool a, std::string b) //断言函数
	{
		if (!a)
		{
			std::cout << b << std::endl;
		}
	}
	int maxsize;//最大容量
	int top;//栈顶索引
	E* listArrey;//数组
public:
	Stack(int size = 20)//构造函数,默认大小为20
	{
		maxsize = size;
		top = 0;//栈顶为0,即还没有放元素
		listArrey = new E[size];
	}
	~Stack() {
		delete[] listArrey;
	}

	void clear() {	//清空栈
		top = 0;
	}
	void push(const E& it) { //压栈
		Assert(top != maxsize, "Stack is full");
		listArrey[top++] = it;//操作顺序是:先赋值,再自增,top会一直指向一个空位置
	}
	E pop() {
		Assert(top != 0, "Stack is empty");
		return listArrey[--top];//操作顺序:先自减,再返回
	}
	const E& topValue() {	//取栈顶元素但是不删除
		Assert(top != 0, "Stack is empty");
		return listArrey[top - 1];
	}
	int length() { //读取堆中已占用的长度
		return top;
	}
	void print() {
		for (int i = 0; i < length(); i++)
		{
			std::cout << listArrey[i] << " ";
		}
		std::cout << std::endl;
	}
	void adjust(int n) {	//用于调整栈的大小
		Assert(n>length(),"New size is too small");
		maxsize = n;
		listArrey = new E[n];
	}
};

test.cpp

#include"Stack.h"


int main() {
	Stack<int> a;
	for (int i = 1; i <= 10; i++)
	{
		a.push(i);
	}
	a.print();
	
	while (a.topValue()!= 5 )
	{
		std::cout << a.pop() << std::endl;
	}
	a.print();
	a.adjust(6);
	return 0;
}

测试结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值