栈的相关知识及栈的实现

栈是一种常用的数据结构,通常称为FILO。

栈通常分为3种:

(1) 数据结构意义的:栈(FILO);

(2) 虚拟地址空间: 栈(虚拟内存分段);

(3) 栈桢: 栈(运行程序时为了保存数据二开辟的空间,随着函数的调用而不断压栈,随着函数的调用结束 而销毁);

栈的数据结构图示:


栈通常用顺序表来实现。

template <typename T>                 //定义一个类模板,对于栈来进行操作
class Stack
{
private:
	T *top;                       //定义一个栈顶指针,用来维护栈
	int _sz;                      //_sz来保存栈的大小
	int _capacity;                //_capacity保存栈的容量
protected:
	void CheckCapacity();
public:
	Stack();                      //构造函数
	~Stack();                     //析构函数
	void Pop();                   //出栈
	void Push(const T x);         //压栈
	bool Empty();                 //检查这个栈是不是为空栈,若为空,返回true
	int GetSize();                //获取栈的大小           
	 T   GetTop();                //获取栈顶元素
	void Print();                 打印栈中的所有元素
};



源代码:

#include<iostream>
using namespace std;
#include<cassert>
template <typename T> 
class Stack
{
private:
	T *top;
	int _sz;
	int _capacity;
protected:
	void CheckCapacity();
public:
	Stack();
	~Stack();
	void Pop();
	void Push(const T x);
	bool Empty();
	int GetSize();
	 T   GetTop();
	void Print();
};

template <typename T> 
Stack<T>::Stack()
	:top(NULL)
	,_sz(0)
	,_capacity(0)
{}
template <typename T> 
Stack<T>::~Stack()
{
	if(top != NULL)
	{
		delete[] top;
		top = NULL;
	}
}
template <typename T> 
void Stack<T>::Pop()
{
	assert(top);
	this->_sz--;

}
template <typename T>
void Stack<T>:: CheckCapacity()
{
	if(this->_capacity == this->_sz)
	{
		int NewCapacity = this->_capacity * 2+5;
		int *tmp = new T[NewCapacity];
		for(int i=0;i<this->_sz;i++)
		{
			tmp[i] = top[i];
		}
		delete [] top;
		top = tmp;
		this->_capacity = NewCapacity; 
	}
}

template <typename T> 
void Stack<T>:: Push(const T x)
{
	CheckCapacity();
	this->top[_sz]=x;
	this->_sz++;
}

template <typename T> 
bool Stack<T>:: Empty()
{
	if(top == NULL)
	{return true;}
	else
	{return false;}
}

template <typename T> 
int Stack<T>:: GetSize()
{
	return --this->_sz;
}

template <typename T> 
T Stack<T>:: GetTop()
{
	return this->top[this->_sz];
}

template <typename T> 
void Stack<T>:: Print()
{
	for(int i=this->_sz;i>=0;i--)
	{
		cout<<this->top[i]<<" ";
	}
	cout<<endl;
}


测试代码:

void TestStack()
{
	Stack<int> stack1;
	stack1.Push (1);
	stack1.Push (2);
	stack1.Push (3);
	stack1.Push (4);
	stack1.Push (5);
	stack1.Push (6);
	stack1.Push (7);
	stack1.Push (8);
	stack1.Push (9);
	stack1.Push (10);
	stack1.Push (11);
	int empty=stack1. Empty();
	int size=stack1. GetSize();
	int top=stack1.GetTop();
	stack1.Print ();
	cout<<"this stack is NULL"<<empty<<endl;
	cout<<"this stack  size is"<<size<<endl;
	cout<<"this stack  top element is"<<top<<endl;
	stack1.Pop ();
	stack1.Pop ();
	stack1.Print ();
	
}
int main()
{
	TestStack();
	system("pause");
	return 0;
}

测试结果:






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值