编程语言
首页 > 编程语言> > 顺序栈C++实现

顺序栈C++实现

作者:互联网

顺序栈C++实现
myStack.h

#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 100
#include<string>


template<typename T>
class myStack
{
public:
	//栈的初始化
	myStack();
	myStack(const myStack& s);
	//判断栈是否为空
	bool isEmpty();
	//求栈的长度
	int size();
	//获取栈顶元素
	T topValue();
	//打印栈中元素(逆序)
	void printElem();
	//清空栈
	void clear();
	//入栈
	void push(T data);
	//出栈
	void pop();
	//栈销毁
	~myStack();
	//运算符重载
	myStack<T>& operator=(myStack<T>& ms);

private:
	T *base;
	T *top;
	int stacksize;
};


//=运算符重载
template<typename T>
myStack<T>& myStack<T>::operator=(myStack<T>& ms)
{
	ms.top -= ms.stacksize;
	for (int i = 0; i < ms.stacksize; i++)
	{
		*top = *ms.top;
		ms.top++;
		top++;
	}
	this->stacksize = ms.stacksize;
	return *this;
	
}
//栈的初始化
template<typename T>
myStack<T>::myStack()
{
	base = new T[MAXSIZE];
	top = base;
	stacksize = 0;
	
}
template<typename T>
myStack<T>::myStack(const myStack& s)
{
	base = new T[MAXSIZE];
	top = base;
	T *temp;
	temp = s.top;
	temp -= s.stacksize;
	for (int i = 0; i < s.stacksize; i++)
	{
		*top = *temp;
		temp++;
		top++;
	}
	this->stacksize = s.stacksize;
}
//判断栈是否为空
template<typename T>
bool myStack<T>::isEmpty()
{
	if (base == top)
		return true;
	else
		return false;
}
//求栈的长度
template<typename T>
int myStack<T>::size()
{
	return stacksize;
}
//获取栈顶元素
template<typename T>
T myStack<T>::topValue()
{
	return *(top - 1);
}
//打印栈中元素(逆序)
template<typename T>
void myStack<T>::printElem()
{
	if (!isEmpty())
	{
		
		for (int i = 1; i <= stacksize; i++)
		{
			cout << *(top - i) << " ";
		}
		cout << endl;
	}
	else
	{
		cout << "栈为空!" << endl;
	}
	
}
//清空栈
template<typename T>
void myStack<T>::clear()
{
	stacksize = 0;
	top = base;
	cout << "清楚成功\n";
}
//入栈
template<typename T>
void myStack<T>::push(T data)
{
	if (top - base != MAXSIZE)
	{
		*top++ = data;
		stacksize++;
		cout << "添加成功\n";
	}
	else
	{
		cout << "栈已满,插入失败!" << endl;
	}
	
}
//出栈
template<typename T>
void myStack<T>::pop()
{
	top--;
	stacksize--;
	cout << "出栈成功\n";
}
//栈销毁
template<typename T>
myStack<T>::~myStack()
{
	delete[] base;
	
}





标签:顺序,实现,top,C++,base,template,myStack,stacksize,void
来源: https://blog.csdn.net/gengjingsai/article/details/121844027