#include<iostream>
using namespace std;
//节点
template<typename T>
class Node
{
public:
Node() { this->data = NULL; this->next = nullptr; }
Node(T _data) { this->data = _data; this->next = nullptr; }
~Node() { if (this->next != nullptr) { this->next = nullptr; } }
//数据域
T data;
//指针域
Node* next;
};
//链表管理类
template<typename T>
class linkList
{
public:
//构造
linkList() { this->length = 0; this->L = new Node<T>; this->L->next = nullptr; }
//析构 在此处应把链表中的节点清空,避免内存泄露
~linkList() { if (this->L != nullptr) { removeList(); delete this->L; } cout << "链表销毁!" << endl; }
//插入节点
void insertList(int loc,T data)
{
//插入前准备
Node<T>* p = new Node<T>(data);
//插入位置判断
if (loc <= 1)//头插
{
p->next = L->next;
L->next = p;
length++;
}
else if (loc > 1 && loc < length)//中间插
{
Node<T>* temp = L;
for (int i = 0; i < loc; i++) { temp = temp->next; }
p->next = temp->next;
temp->next = p;
length++;
}
else if (loc >= length)//尾插
{
Node<T>* temp = L;
for (int i = 0; i < length; i++){temp = temp->next;}
p->next = temp->next;
temp->next = p;
length++;
}
}
//删除节点
void deleteList(int loc)
{
Node<T>* temp = L;
if (loc <= 1)//头删
{
Node<T>* _temp = temp->next;
L->next = _temp->next;
delete _temp;
length--;
}
else if (loc > 1 && loc < length)//中间删
{
for (int i = 0; i < loc - 1; i++) {temp = temp->next;}
Node<T>* _temp = temp->next;
temp->next = _temp->next;
delete _temp;
length--;
}
else if (loc >= length)//尾删
{
for (int i = 0; i < length - 1; i++) {temp = temp->next;}
Node<T>* _temp = temp->next;
temp->next = nullptr;
delete _temp;
length--;
}
}
//遍历节点
void printList()
{
Node<T>* temp = L;
for (int i = 0; i < length; i++) { temp = temp->next; cout << temp->data << "\t"; }
cout << endl;
}
//清空节点
void removeList()
{
Node<T>* temp = L->next;
for (int i = 0; i < length; i++)
{
Node<T>* _temp = temp->next;
delete temp;
temp = _temp;
}
length = 0;
}
//元素查找
void findList(T data)
{
Node<T>* temp = L;
for (int i = 0; i < length; i++)
{
temp = temp->next;
if (temp->data == data) {cout << "位置:" << i + 1 << "\t数据:" << temp->data << endl;}
}
cout << "查找完毕!" << endl;
}
//获取表长
int getList() { return this->length; }
//获取头节点
Node<T>* getNode() { return L; }
private:
//记录当前长度
int length;
//记录指针
Node<T>* L;
};