【C++数据结构】模板链栈

来源:互联网 发布:2017网络事件 编辑:程序博客网 时间:2024/06/08 04:16

Stack.h

template<class T>class Link {public:    Link();public:    T data = NULL;    Link* next = nullptr;};template<class T>class CStack{public:    CStack();    ~CStack();private:    Link<T>* top = nullptr;    Link<T>* end = nullptr;public:    void Push(T data); // 压入栈    T Pop(void);    // 压出栈    int GetLength(void); // 得到长度    T& At(int i);  //返回第i个数据 若i大于length或小于0 则返回0};

Stack.cpp

#include "Stack.h"template<class T>Link<T>::Link(){}template<class T>CStack<T>::CStack(){}template<class T>CStack<T>::~CStack(){    while (nullptr != top) {        Link<T>* node = top;        top = top->next;        delete node;        node = nullptr;    }}template<class T>void CStack<T>::Push(T data){    if (nullptr == top) {        top = new Link<T>;        top->data = data;        top->next = nullptr;        end = top;        return;    }    Link<T>* newNode = new Link<T>;    newNode->data = data;    newNode->next = nullptr;    end->next = newNode;    end = newNode;}template<class T>T CStack<T>::Pop(void){    if (nullptr == top) {        return NULL;    }    T reVal = end->data;    if (top == end) {        delete end;        top = end = nullptr;        return reVal;    }    Link<T>* node = top;    while (node->next != end)    {        node = node->next;    }    Link<T>* tempNode = end;    end = node;    delete tempNode;    tempNode = nullptr;  //  delete之后一定要设置指针为空 否则 前一个指针的->next 仍然指着这个被删掉的区域    return reVal;}template<class T>int CStack<T>::GetLength(void){    int length = 0;    Link<T>* node = top;    while (nullptr != node) {        node = node->next;        length++;    }    return length;}template<class T>T& CStack<T>::At(int index)//返回对象的引用{    T empty = NULL;    int length = GetLength();    if (index >= length || index < 0) {        return empty;    }    Link<T>* node = top;    for (int i = 0; i < length; i++, node = node->next) {        if (i == index) {            return node->data;        }    }}

源.cpp

#include "Stack.h"#include "Stack.cpp"  // 因为使用了模板void main() {    CStack<int> s;    for (int i = 0; i < 10; i++) {        s.Push(i);    }    for (int i = 0; i < 10; i++) {        cout << s.Pop() << endl;    }    system("pause");}
0 0
原创粉丝点击