栈是一种特殊的线性表,主要是先进后出。

主要函数包括:压栈、出栈、清空栈、栈长度

主要代码如下:

#include <iostream>
using namespace std;

template<class T>
class sstackNode
{
public:
	sstackNode(){next=0;}
	T data;
	sstackNode<T> *next;
};

template <class T>
class Mystack
{
public:
	Mystack();//初始化
	unsigned int MystackLength();//返回栈的长度
	void push(T x);//入栈
	void pop();//出栈
	T top();//获取栈顶数据
	void clear();//清空栈
	bool isEmpty();//判断是否为空
private:
protected:
	unsigned int stacklength;
	sstackNode <T> *node;
	sstackNode <T> *headnode;
};
template <class T>
Mystack<T>::Mystack()//初始化
{
	stacklength	=0;
	headnode=NULL;
}
template <class T>
unsigned int Mystack<T>::MystackLength()//返回栈的长度
{
	return stacklength;
}

template <class T>
void Mystack<T>::push(T x)//入栈
{
	node=new sstackNode<T>();
	node->data=x;
	if (headnode==NULL)
	{
		node->next=NULL;
	}
	else
	{
		node->next=headnode;
	}
	headnode=node;
	stacklength++;
}

template <class T>
void Mystack<T>::pop()//出栈
{
	if (headnode==NULL)
	{
		return;
	}
	else
	{
		if (headnode->next=NULL)
		{
			delete(headnode);
			headnode=NULL;
		}
		else
		{
			node=headnode;
			headnode=node->next;
			delete(node);	
			node=NULL;
		}
		stacklength--;
	}
}

template <class T>
T Mystack<T>::top()//获取栈顶数据
{
	return(headnode->data);
}

template <class T>
void Mystack<T>::clear()//清空栈
{
	if (headnode==NULL)
	{
		return;
	}
	while(headnode!=NULL)
	{
		node=headnode;
		headnode=headnode->next;
		delete(node);
		node=NULL;
	}
	stacklength=0;
}

template <class T>
bool Mystack<T>::isEmpty()//判断是否为空
{
	if (0==stacklength)
	{
		return true;
	}
	else
		return false;
}

  

原文地址:https://www.cnblogs.com/lanye/p/3240403.html