**
1.代码
**
single_list.cpp
#include <iostream>
//节点类
template<typename T>
struct node{
T data;
node<T>* m_pnext;
node(){
data = T();
m_pnext = nullptr;
}
};
//单链表类
template<typename T>
struct single_list{
int m_length; //链表长度
node<T>* m_pcurrent; //链表当前指向节点
single_list():m_length(0),m_pcurrent(nullptr){};
//链表大小
int size(){ return m_length; }
//插入节点
int insert(const T& value)
{
node<T>* new_elem = new node<T>();
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<T>* p = m_pcurrent;
node<T>* 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<T>* elem)
{
node<T>* 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<T>* p = m_pcurrent;
node<T>* q = nullptr;
while(p!=nullptr){
q = p->m_pnext;
delete p;
p = q;
}
m_pcurrent = nullptr;
m_length = 0;
}
};
//测试
int main()
{
single_list<int> sl;
for(int i = 0;i<=10;i++)
{
sl.insert(i);
}
std::cout<<"sl.size(): "<<sl.size()<<std::endl;
sl.erase(5);
node<int>* pfind = new node<int>;
pfind->data = 4;
std::cout<<"the value of 4's index: "<<sl.index(pfind)<<std::endl;
node<int>* ptmp = sl.m_pcurrent;
while(ptmp != nullptr){
std::cout<<ptmp->data<<std::endl;
ptmp = ptmp->m_pnext;
}
sl.clear();
std::cout<<"after clear: size():"<<sl.size()<<std::endl;
return 1;
}
编译
$g++ single_list.cpp -o sl --std=c++11
$./sl
运行结果: