单链表的基本实现

来源:互联网 发布:中小型国有企业知乎 编辑:程序博客网 时间:2024/04/29 10:35

按照自己的喜好和风格总结了下,PS. 到底是节点还是结点呢,好纠结……

1. 节点类

template<typename Object>struct Node{    Object data;    Node<Object> *next;    Node(const Object &oTemp=Object(), Node<Object> *pTemp=0): data(oTemp), next(pTemp) {}};

2. 链表的建立

template<typename Object>Node<Object> * CreateList()    //用这种方式调用CreateList<int>(),意外收获{    Node<Object> *pHead=new Node<Object>;    Node<Object> *pCurr=pHead;    Object oTemp;    cout<<"输入节点数据,^Z结束:"<<endl;    while (cin>>oTemp)    {        pCurr->next=new Node<Object> (oTemp);        pCurr=pCurr->next;    }    pCurr=pHead;    pHead=pHead->next;    delete pCurr;    return pHead;}

3. 链表的打印和测长

template<typename Object>void PrintList(Node<Object> *pCurr){    if (pCurr==0)    {        cout<<"链表为空"<<endl;        return;    }    while (pCurr)    {        cout<<pCurr->data<<" ";        pCurr=pCurr->next;    }    cout<<endl;}template<typename Object>int LengthOfList(Node<Object> *pCurr){    int oCount=0;    while (pCurr)    {        ++oCount;        pCurr=pCurr->next;    }    return oCount;}

4. 链表节点的删除(找到第一个含有某值的节点并删除)

template<typename Object>void DeleteNode(Node<Object> **pHead, const Object &delValue){    if (0==pHead || 0==*pHead)    {        cout<<"无效链表"<<endl;        return;    }    Node<Object> *pDel=0;    if ((*pHead)->data==delValue)    {        pDel=*pHead;        *pHead=(*pHead)->next;    }    else    {        Node<Object> *pCurr=*pHead;        while (pCurr->next !=0 && pCurr->next->data != delValue)        {            pCurr=pCurr->next;        }        if (pCurr->next)        {            pDel=pCurr->next;            pCurr->next=pDel->next;        }    }    if (pDel)    {        delete pDel;        cout<<"目标节点已删除"<<endl;    }    else    {        cout<<"目标节点不存在"<<endl;    }}

5. 链表节点的插入(在有序链表中插入含有某个值的节点)

template<typename Object>void InsertNode(Node<Object> **pHead, const Object &insValue)    //在有序链表中插入{    if (0==pHead)    {        cout<<"无效链表"<<endl;        return;    }    if (0==*pHead)    {        *pHead=new Node<Object> (insValue);    }    else if (insValue < (*pHead)->data)    {        *pHead=new Node<Object> (insValue, *pHead);    }    else    {        Node<Object> *pCurr=*pHead;        while (pCurr->next && insValue > pCurr->next->data)        {            pCurr=pCurr->next;        }        if (pCurr->next)        {            pCurr->next=new Node<Object> (insValue, pCurr->next);        }        else        {            pCurr->next=new Node<Object> (insValue, 0);        }    }}

原创粉丝点击