shiyan15_2.cpp

来自「为初学者提供的最佳的C++程序设计源程序库」· C++ 代码 · 共 93 行

CPP
93
字号
//--------类模板:栈-------//
#include"iostream.h"
struct node_int
{
	int data;
	struct node_int *next;
};
struct node_person
{
	char *pName;
	bool Gender;
	int Age;
	struct node_person *next;
};

template<class T>
class Stack
{
public:
	T *pBottom;
	T *pTop;
	Stack()
	{
		pBottom=NULL;
		pTop=NULL;
	};
	T *Pop();
	void Push(T & newnode);
	void Clear();
};

template<class T>
void Stack<T>::Clear()
{
	if(pTop==NULL)
		return;
	T *temp;
	while(pTop!=pBottom)
	{
		temp=pTop;
		pTop=pTop->next;
		delete temp;
	}
	delete pBottom;
    pBottom=pTop=NULL;
	return;
}
template<class T>
void Stack<T>::Push(T & newnode)
{
	if(pBottom==NULL)
	{
		pBottom=&newnode;
		pTop=pBottom;
		pBottom->next=NULL;
		return;
	}
	newnode.next=pTop;
	pTop=&newnode;
	return;
}
template<class T>
T *Stack<T>::Pop()
{
	T *out;
	if(pTop==NULL)
	{
		cout<<"\nthe stack is empty,can not pop"<<endl;
		return NULL;
	}
	out=pTop;
	pTop=pTop->next;
	return out;
}
void main()
{
	Stack<node_int>s1;
	node_int *pTemp=new node_int();
	pTemp->data=8;
	s1.Push(*pTemp);
	s1.Clear();
	Stack<node_person>s2;
	node_person *person=new node_person();
	person->pName="hehe newperson name";
	s2.Push(*person);
	s2.Pop();
	return;
}


		
				

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?