C++实现单链表

**

1.代码

**
single_list.cpp

#include 

//节点类
template
struct node{
    T data;
    node* m_pnext;

    node(){
        data = T();
        m_pnext = nullptr;
    }
};

//单链表类
template
struct single_list{
    int m_length;	//链表长度
    node* m_pcurrent;	//链表当前指向节点

    single_list():m_length(0),m_pcurrent(nullptr){};

	//链表大小
    int size(){ return m_length; }

	//插入节点
    int insert(const T& value)
    {
        node* new_elem = new node();
        new_elem->data = value;
        if(size() == 0){
            m_pcurrent = new_elem;
        }else{
            new_elem->m_pnext = m_pcurrent;
            m_pcurrent = new_elem;
        }
        m_length++;
    }

	//删除节点
    int erase(const T& value)
    {
        node* p = m_pcurrent;
        node* q = m_pcurrent;

        while(p != nullptr){
            if(p->data == value){
                q->m_pnext = p->m_pnext;
                m_length--;
                break;
            }else{
                q = p;
                p = q->m_pnext;
            }
       }
    }

	//节点所在索引
    int index(const node* elem)
    {
        node* p = m_pcurrent;
        int idx = -1;
        while(p!=nullptr){
            if(p->data != elem->data){
                p = p->m_pnext;
                ++idx;
            }else{
                break;
            }
        }

        return ++idx;
    }

	//链表是否为空
    bool empty()
    {
        return m_length == 0;
    }

	//清除链表
    void clear()
    {
        node* p = m_pcurrent;
        node* q = nullptr;
        while(p!=nullptr){
            q = p->m_pnext;
            delete p;
            p = q;
        }

        m_pcurrent = nullptr;
        m_length = 0;
    }
};

//测试
int main()
{
    single_list sl;

    for(int i = 0;i<=10;i++)
    {
        sl.insert(i);
    }


    std::cout<<"sl.size(): "<* pfind = new node;
    pfind->data = 4;
    std::cout<<"the value of 4's index: "<* ptmp = sl.m_pcurrent;
    while(ptmp != nullptr){
        std::cout<data<m_pnext;
    }

    sl.clear();
    std::cout<<"after clear: size():"<

编译

$g++ single_list.cpp -o sl --std=c++11
$./sl

运行结果:
C++实现单链表_第1张图片

你可能感兴趣的:(C及C++,单链表)