[数据结构]链表的实现(c++/类模板)

#include <iostream>
#include <cstdlib>
using namespace std;

//用struct定义LinkNode类.使用这种方法使该类失去封装性,但简化了描述.
//在Link类中把first封装在了其内部,属于该Link的所有LinkNode实例都成为Link实例的私有成员,保证不被外界直接访问.

//结点模板的定义
template<typename Type>
struct LinkNode
{
    Type data;
    LinkNode<Type>* next;
    LinkNode(const Type& item, LinkNode<Type>* ptr=NULL)//用于初始化data和next
    {
        data = item;
        next = ptr;
    }
    /*    LinkNode(LinkNode<Type>* ptr=NULL)
        {
            next = ptr;
        }
    */
};
//单链表模板的定义
template<typename Type>
class List
{
private:
    LinkNode<Type>* first;//链表头指针
public:
    List()//构造函数
    {
        first = NULL;
    }
    List(const List<Type>& L)//拷贝构造函数
    {
        first = NULL;
        CopyList(L);
    }
    List<Type>operator=(const List<Type>& L)//赋值运算符符号
    {
        if(this==&L)
            return *this;
        MakeEmpty();
        CopyList(L);
        return *this;
    }
    ~List()//析构函数
    {
        LinkNode<Type>* p;
        while(p)
        {
            p=first;
            first=p->next;
            delete p;
        }
    }

    //单链表的增删查改
    void InputFront(const Type& elem);
    void InputRear(const Type& elem);
    bool Insert(int i, const Type& x);
    bool Remove(int i, Type& x);
    //LinkNode<Type>* Search(const Type& x);
    bool Search(const Type& x);
    LinkNode<Type>* Locate(int i);
    bool GetData(int i, Type& x)const;
    bool SetData(int i, const Type& x);

    //清空复制列表结点
    void MakeEmpty();
    void CopyList(const List<Type>& L);

    //链表自身状态
    int Length() const
    {
        LinkNode<Type>* s=first;
        int count=1;
        while(s->next)
        {
            count++;
            s = s->next;
        }
        return count;
    }
    bool IsEmpty() const
    {
        return first==NULL;
    }
    bool IsFull() const
    {
        return false;
    }

    //当前指针所指向结点在链表中的位置
    int GetLocation(const LinkNode<Type>* iter)
    {
        LinkNode<Type>* p = first;
        int L = Length();
        int count = 0;
        while(count <= L)
        {
            count++;
            if(p==iter)
            {
                return co
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值