#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;
};