C++栈类模板与应用

.前言
栈是只能从一段访问的线性群体,是一种后进先出的数据结构。

.特点
1、栈中的元素遵守“先进后出”(First In Last Out)的原则,简称FILO结构。
2、限定只能在栈顶进行插入和删除操作。

注:函数调用和返回的过程底层处理都是依靠栈实现的

.基本操作
1、弹栈,通常命名为pop
2、压栈,通常命名为push
3、求栈的大小
4、判断栈的状态(满、空)
5、获取栈顶元素的值
6、初始化
7、清空栈

.栈类模板代码

#ifndef STACK_H
#define STACK_H
#include <cassert>
template<class T,int SIZE =50>
class Stack
{
    
    
public:
	Stack();                 //构造函数
	void push(const T& item);//压入栈
	T pop();                 //出栈
	void clear();            //清空栈
	const T& peek() const;   //读取栈元素
	bool isEmpty() const;    //判断是否为空
	bool isFull() const;     //判断是否为满
private:
	T list[SIZE];            //存放元素
	int top;                 //指向栈顶的指针
};
//模板的实现
template <class T, int SIZE>
Stack<T, SIZE>::Stack():top(-1)//在建立一个栈的时候是没有元素的,在放入第一个元素后top才会变为0
{
    
    
	
}
template <class T, int SIZE>
void Stack<T, SIZE>::push(const T& item)
{
    
    
	assert(!isFull());
	list[++top] = item;//先加后压入
}
template <class T, int SIZE>
T Stack<T, SIZE>::pop()
{
    
    
	assert(!isEmpty());
	return list[top--];//先弹出后减
}
template <class T, int SIZE>
const T& Stack<T, SIZE>::peek() const
{
    
    
	assert(!isEmpty());
	return list[top];//返回栈顶元素
}
template <class T, int SIZE>
bool Stack<T, SIZE>::isEmpty() const
{
    
    
	return top == -1;
}
template <class T, int SIZE>
bool Stack<T, SIZE>::isFull() const
{
    
    
	return top == SIZE-1;
}
template <class T, int SIZE>
void Stack<T, SIZE>::clear()
{
    
    
	top = -1;
}

#endif STACK_H

猜你喜欢

转载自blog.csdn.net/qq_43530773/article/details/114376693