数据结构作业——链栈的实现

本文介绍了链栈的概念,特别是采用C++通过void指针实现的通用链栈,利用模板类支持多种数据类型。文中提供了具体的实现代码。
摘要由CSDN通过智能技术生成

数据结构作业——链栈的实现

介绍

链栈,即为使用链式存储的栈。
本程序使用void指针指向不同类型的链栈头结点,使用的时候强制转换即可。
用template实现了存储不同数据类型。

实现代码

#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
const int maxn = 9;
struct stack_node
{
   
	void * root;
	int data_type; // 1 int 2 double 3 char
}st[maxn + 1];
template<class T>struct node
{
   
	T data;
	node<T>*next;
};
template<class T>void des_stack(int root)
{
   
	node<T>*pointer = (node<T>*)st[root].root;
	node<T>*pointer2;
	while (pointer2 = pointer->next)
	{
   
		free(pointer);
		pointer = pointer2;
	}
	free(pointer);
	st[root].root = NULL;
	st[root].data_type = 0;
}
template<class T>bool stack_top(int root, T &ans)
{
   
	node<T>*pointer = (node<T>*)st[root].root;
	if (pointer->next == NULL) return 0;
	ans = pointer->data;
	return 1;
}
template<class T>void stack_push(int root, T data)
{
   
	node<T>*temp_pointer = (node<T>*)malloc(sizeof(node<T>));
	temp_pointer->data = data;
	temp_pointer->next = (node<T>*)
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值