7.8下午笔记

该博客介绍了C++中使用模板类SeqStack实现栈的数据结构,并展示了如何进行元素的压入、弹出、获取栈顶元素等操作。示例代码创建了一个整数类型的SeqStack对象,将一系列整数压入栈,然后逐一弹出并打印,体现了栈的先进后出特性。
摘要由CSDN通过智能技术生成

构造函数用于获取资源! 

构造函数返回值返回的是地址

析构函数返回值

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
using namespace std;

template<class Type>
class SeqStack//栈 先进后出
{
private://私有数据成员
	Type* data;//数据
	int maxsize;//最大长度
	int top;//栈顶
public://公有成员
	SeqStack(int sz = 10) :maxsize(sz), top(-1)//最大栈长为10  top为-1
	{
		data = (Type*)malloc(sizeof(Type) * maxsize);//malloc 动态内存分配但没有指定名字
		if (data == NULL)exit(1);
	}
	~SeqStack()//析构函数
	{
		free(data);//释放
		data = NULL;
		maxsize = 0;
		top = -1;
	}
	int GetSize() const { return top + 1; }//逐次加一
	bool Is_Empty() const { return GetSize()==0; }
	bool Is_Full() const { return GetSize() == maxsize; }//若满则为最大长度
	bool Push(const Type& x)
	{
		if (Is_Full()) return false;
		data[++top] = x;
		return true;
	}
	Type& GetTop()
	{
		return data[top];
	}

	const Type& GetTop() const
	{
		return data[top];
	}
	void Pop()
	{
		--top;
	}
};

int main()
{
	SeqStack<int> ist = SeqStack<int>();
	ist.Push(12);
	ist.Push(23);
	ist.Push(34);
	ist.Push(45);
	while (!ist.Is_Empty())
	{
		int x = ist.GetTop();
		ist.Pop();
		cout << x << endl;
	}
	return 0;
}

栈:先进后出

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值