栈链式存储结构的C++模板类源代码

采用链表的结构表示栈,具体修改类的成员函数,栈可以视为限制为特定功能的链表结构,每压入一个元素就动态分配内存,弹出元素时释放内存,析构的时候释放整个链表,此处应注意,链表的头指针也是一个动态分配的内存,注意在构造函数中分配和析构中释放。下面是栈链式存储的模板类头文件源代码:

//linkedstack.h
#ifndef LINKEDSTACK_H
#define LINKEDSTACK_H
#include <IOSTREAM>
template<class Type>
struct Node
{
Type data;
Node<Type>* next;
};
template<class Type>
class LinkedStack
{
private:
Node<Type>* head;
public:
LinkedStack();
~LinkedStack();
bool Push(Type);
Type Pop(); 
bool IsEmpty();
void Print();
};
template<class Type>
LinkedStack<Type>::LinkedStack()
{
head=new Node<Type>;
head->data=-111;
head->next=NULL;
}
template<class Type>
LinkedStack<Type>::~LinkedStack()
{
Node<Type>* temp=head;
while(temp)
{
Node<Type>* tempvalue=temp;
temp=temp->next;
delete tempvalue;
}
}
template<class Type>
bool LinkedStack<Type>::Push(Type temp)
{ 
Node<Type>* now=head;
Node<Type>* nowbefore=now;
while(now)
{
nowbefore=now;
now=now->next;
}
Node<Type>* element=new Node<Type>;
element->data=temp;
element->next=NULL;
nowbefore->next=element;
return true;
}
template<class Type>
Type LinkedStack<Type>::Pop()
{
if(IsEmpty())
return Type(-111);
Node<Type>* now=head->next;
Node<Type>* nowbefore=head;
Node<Type>* nowbeforebefore=NULL;
while(now)
{
nowbeforebefore=nowbefore;
nowbefore=now;
now=now->next;
} 
nowbeforebefore->next=NULL;
Type exam=nowbefore->data;
delete nowbefore;
return exam;
}
template<class Type>
bool LinkedStack<Type>::IsEmpty()
{
if(head->next)
return false;
else
return true;
}
template<class Type>
void LinkedStack<Type>::Print()
{
Node<Type>* temp=head->next;
while(temp)
{
std::cout<<temp->data<<" ";
temp=temp->next;
}
std::cout<<std::endl;
}
#endif

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值