C++数据结构---栈

stack.h

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

class Mystack
{
public:
	Mystack();

	//打印栈中的数据(从栈顶到栈底)
	void Mystack::m_print();
	//在栈顶添加元素
	void m_push(int val);
	//从栈顶移除第一个元素
	void m_pop();
	//返回栈顶元素
	int m_top();
	//判断堆栈是否为空
	bool m_empty();
	//返回栈的大小
	int m_size();

	int* button;//栈低的地址
	int top;//栈顶是是第几个元素,相当于size
	int capacity;//容器的大小
};

Mystack::Mystack()//初始化成员属性
{
	button = new int[4];
	top = 0;
	capacity = 4;//初始化为四,避免刚开始就需要增容
}

//打印栈中的数据(从栈顶到栈底)
void Mystack::m_print()
{
	for (int i = 0; i < this->top; i++)
	{
		cout << *(this->button + i) << "\t";
	}
	cout << endl;
}


//拷贝函数
void m_copy(int* f, int* n,int size)
{
	for (; size > 0; n++,f++, size--)
	{
		*n = *f;
	}
}

//插入数据
void Mystack::m_push(int val)
{
	if (this->top == this->capacity)
	{
		int* newstack = new int[this->capacity * 2];//创建一个新的数组是原数组的2倍大小
		m_copy(this->button, newstack, this->top);		//将原数组拷贝到新数组上
		delete[] button;
		this->button = newstack;
		*(button + top) = val;//插入数值
		//更新状态
		this->capacity *= 2;
		this->top++;
	}
	else
	{
		*(button + top) = val;
		this->top++;
	}
}

//从栈顶移除第一个元素
void Mystack::m_pop()
{
	this->top--;//直接只读到top-1就行
}

//返回栈顶元素
int Mystack::m_top()
{
	return *(this->button + top-1);//当栈中有n个元素,top为n,栈顶元素下标为top-1
}

//判断堆栈是否为空
bool Mystack::m_empty()
{
	if (this->top == 0)
		return true;
	else
		return false;
}

//返回栈的大小
int Mystack::m_size()
{
	return top;
}

stack.cpp

int main()
{
	Mystack s;
	s.m_push(1);
	s.m_push(2);
	s.m_push(3);
	s.m_push(4);
	s.m_push(5);
	s.m_push(6);
	s.m_print();
	s.m_pop();
	s.m_print();
	cout << "栈顶的元素为:" << s.m_top() << endl;
	bool f = s.m_empty();
	cout << f << endl;
	s.m_pop();
	s.m_print();
	cout << "栈中元素的个数" << s.m_size() << endl;
	s.m_print();
	return 0;
}

结果图。

有错希望评论交流,如果有帮助的话,点个赞吧!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值