栈的链式存储--c++版本

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

通过类中的top指针就可以操作整张链表

在这里插入图片描述

在这里插入图片描述

stack.hpp

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
//节点结构体
template<class Data>
struct node {
    
    
	Data data;
	node<Data>* next;
};
//链表类
template<class Data>
class LinkStack 
{
    
    
private:
	node<Data>* top;
public:
	//不需要有参构造函数
	LinkStack();
	~LinkStack();
	void push(Data val);
	void pop();
	Data getTop();
	bool isEmpty();
	class Empty{
    
    };
};
template<class Data>
LinkStack<Data>::LinkStack()
{
    
    
	//这里用的是无头链表
	top = NULL;
};
template<class Data>
void LinkStack<Data> :: push(Data val)
{
    
    
	//在堆区开辟一块空间,来存放第一个节点
	node<Data>* newNode = new node<Data>;
	newNode->data = val;
	//无头链表的头插法
	newNode->next = top;
	//链表指向第一个节点
	top = newNode;
}
template<class Data>
void LinkStack<Data>::pop()
{
    
    
	//如果链表为空,就抛出异常
	if (top == NULL)
	{
    
    
		throw Empty();
	}
	//不为空,进行头删的操作
	//先释放再头删
	//注意要保存住被删除1的节点
	node<Data>* temp = top;
	//注意:要先把top移到下一个节点,再进行释放操作
	top = top->next;
	delete temp;
}
template<class Data>
Data LinkStack<Data>::getTop()
{
    
    
	if (top == NULL)
		return NULL;
	return top->data;
}
template<class Data>
bool LinkStack<Data>::isEmpty()
{
    
    
	if (top == NULL)
		return true;
	return false;
}
template<class Data>
LinkStack<Data>::~LinkStack()
{
    
    
	while (top)
	{
    
    
		node<Data>* temp = top;
		top = top->next;
		free(temp);
}
	node<Data>* top = NULL;
}

main.cpp

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
#include"stack.hpp"
//测试代码--------------------------------
void test()
{
    
    
	LinkStack<int> s;
	//向栈1中输入元素
		s.push( 1);
		s.push( 2);
		s.push( 3);


	try {
    
    
		//进行打印:栈1和栈2都不为空才进行打印
		while (!s.isEmpty())
		{
    
    
			int temp = s.getTop();
			cout << temp << " ";
			s.pop();
		}
	}
	catch (LinkStack<int>::Empty)
	{
    
    
		cout << "当前堆栈为空,删除失败" << endl;
	}
}
int main()
{
    
    
	test();
	system("pause");
	return 0;
}

在这里插入图片描述
在这里插入图片描述

注意:上面的链式栈中加了异常检测

在模板类中使用模板结构体时要注意:
在这里插入图片描述
类模板与函数模板的区别

猜你喜欢

转载自blog.csdn.net/m0_53157173/article/details/114459581
今日推荐