自定义存放任意类型的链表栈
/*
链表栈
*/
#ifndef _LIST_STACK_H_
#define _LIST_STACK_H_
template<class T>class ListStack;
template<class T>
class Node
{
friend ListStack<T>;
private:
T data;
Node<T> * link;
};
template<class T>
class ListStack
{
public:
ListStack();
~ListStack();
bool isEmpty()const;
int size()const;
T top()const;
void pop();
bool push(const T& t);
private:
Node<T> *nowTop;
int nowSize;
};
template<class T>
ListStack<T>::ListStack() :nowTop(nullptr), nowSize(0)
{
}
template<class T>
ListStack<T>::~ListStack()
{
Node<T>* next;
while (nowTop != nullptr)
{
next = nowTop->link;
delete nowTop;
nowTop = next;
}
}
template<class T>
bool ListStack<T>::isEmpty()const
{
if (nowSize == 0)
return true;
else
return false;
}
template<class T>
int ListStack<T>::size()const
{
return nowSize;
}
template<class T>
T ListStack<T>::top()const
{
if (!isEmpty())
{
return nowTop->data;
}
}
template<class T>
void ListStack<T>::pop()
{
Node<T>* next = nowTop->link;
delete nowTop;
nowTop = next;
nowSize--;
}
template<class T>
bool ListStack<T>::push(const T& t)
{
Node<T> *p = new Node<T>;
p->data = t;
p->link = nowTop;
nowTop = p;
nowSize++;
return true;
}
#endif测试代码:
#include <iostream>
#include <memory>
#include "ListStack.h"
using namespace std;
class A
{
public:
A(){ cout << "A construct!" << endl; }
~A(){ cout << "A destruct!" << endl; }
};
void testListStack()
{
ListStack<shared_ptr<A>> mStack;
mStack.push(make_shared<A>());
mStack.push(make_shared<A>());
mStack.pop();
mStack.pop();
mStack.push(make_shared<A>());
cout << "test" << endl;
}
void main()
{
testListStack();
system("pause");
}
输出:
A construct!
A construct!
A destruct!
A destruct!
A construct!
test
A destruct!
请按任意键继续. . .

这篇博客介绍了如何使用C++实现一个自定义的链表栈,该栈能够存放任意类型的数据。通过模板类的设计,实现了数据类型的泛型化,文章中提到了构造和析构过程,并给出了实例演示。
324





