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

本文介绍了一个基于模板的栈实现,包括栈的基本操作如压栈、弹栈等,并提供了完整的源代码示例。通过C++模板类实现了通用的链式栈结构。

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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值