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