带链栈类

带链栈类也就是链式存储方式的栈:文件名 linked_Stack.h

#include <iostream>
using namespace std;
template <class T>
struct node
{
	T d;
	node * next;
};
template<class T>
class linked_Stack
{
private:
	node<T> *top;
public:
	linked_Stack();
	void prt_linked_Stack();
	int flag_linked_Stack();
	void ins_linked_Stack(T);
	T del_linked_Stack();
	T read_linked_Stack();

};
template<class T>
linked_Stack<T>::linked_Stack()
{
	top=NULL;
	return;

}
template<class T>
void linked_Stack<T>::prt_linked_Stack()
{
	node<T> *p;
	p=top;
	if(p==NULL)
	{
		cout<<"栈为空"<<endl;
		return;

	}
	do 
	{
		cout<<p->d<<endl;
		p=p->next;
	} while (p!=NULL);
	return;
}
template<class T>
int linked_Stack<T>::flag_linked_Stack()
{
	if(NULL==top)return 0;
	return 1;
}
template<class T>
void linked_Stack<T>::ins_linked_Stack(T b)
{
	node<T> *p;
	p=new node<T>;
	p->d=b;
	p->next=top;
	top=p;
	return;


}
template<class T>
T linked_Stack<T>::del_linked_Stack()
{
	T y;
	node<T> *q;
	if(top==NULL)
	{
		cout<<"空栈"<<endl;
		return 0;
	}
	q=top;
	y=q->d;
	top=q->next;
	delete q;
	return y;
}
template<class T>
T linked_Stack<T>::read_linked_Stack()
{
	if(top==NULL)
	{
		cout<<"空栈"<<endl;
		return 0;
	}
	return(top->d);
}


实验实例:

#include "linked_Stack.h"
#include<stdlib.h>
int main()
{
	linked_Stack<int> s;
	s.ins_linked_Stack(50);
	s.ins_linked_Stack(60);
	s.ins_linked_Stack(70);
	s.ins_linked_Stack(80);
	s.ins_linked_Stack(90);
	s.ins_linked_Stack(100);
	cout<<"输出栈中的元素"<<endl;
	s.prt_linked_Stack();
	if(s.flag_linked_Stack())
		cout<<"栈顶元素:"<<s.read_linked_Stack()<<endl;
	if(s.flag_linked_Stack())
		cout<<"退栈元素:"<<s.del_linked_Stack()<<endl;
	if(s.flag_linked_Stack())
		cout<<"退栈元素:"<<s.del_linked_Stack()<<endl;
	cout<<"再次输出栈中的元素"<<endl;
	s.prt_linked_Stack();
	system("pause");
	return 0;



}


实验结果:

带链栈类_第1张图片

你可能感兴趣的:(带链栈类)