#include <iostream>
using std::cout;
using std::endl;
template <typename T>
struct ListNode
{
T data;
ListNode<T>* link;
};
template <typename T>
class List
{
private:
ListNode<T>* head;
public:
List();
int len(); //获取链表的长度
ListNode<T>* get(int pos); //按序号查找节点
void add(int pos, T theData); //任意位置添加节点
void del(int pos); //删除任意位置的节点
void clc(); //清空链表
};
#include "List.h"
template <typename T>
List<T>::List() { head = nullptr; }
//-----获取链表的长度-----------------------------------//
template <typename T>
int List<T>::len()
{
if (head == nullptr)
return 0; //头指针为空的话返回0
else
{
int count = 0;
ListNode<T>* node = head;
while (node != nullptr)
{
count++;
node = node->link;
}
return count; //返回节点个数
}
}
//-----按序号查找节点-----------------------------------//
template <typename T>
ListNode<T>* List<T>::get(int pos)
{
if (head == nullptr)
{
cout << "链表为空!" << endl;
return nullptr;
}
else
{
if (pos >= 0)
{
if (pos < len()) //序号不能超出链表实际长度
{
ListNode<T>* node = head;
for (int i = 0; i < pos; i++)
{
node = node->link;
}
return node;
}
else
{
cout << "序号超出范围!" << endl;
return nullptr;
}
}
else
{
cout << "序号不能为负数!" << endl;
return nullptr;
}
}
}
//-----在任意位置添加节点-------------------------------//
template <typename T>
void List<T>::add(int pos, T theData)
{
if (head == nullptr) //链表为空的情况
{
if (pos == 0)
head = new ListNode<T>{ theData, nullptr };
else if (pos > 0)
cout << "序号超出范围!" << endl;
else
cout << "序号不能为负数!" << endl;
}
else //链表不为空的情况
{
if (pos == 0) //在链表头部插入节点
head = new ListNode<T>{ theData, head };
else if (pos > 0)
{
if (pos <= len()) //在链表中间或尾部插入节点
{
ListNode<T>* node = get(pos - 1); //找到插入点的前一个节点
node->link = new ListNode<T>{ theData, node->link };
}
else
cout << "序号超出范围!" << endl;
}
else
cout << "序号不能为负数!" << endl;
}
}
//-----删除任意位置的节点-------------------------------//
template <typename T>
void List<T>::del(int pos)
{
if (head == nullptr)
cout << "链表为空!" << endl;
else //链表不为空的情况
{
if (pos == 0) //删除头部节点的情况
{
ListNode<T>* node = head;
head = head->link;
delete node;
}
else if (pos > 0)
{
if (pos < len()) //删除中间或尾部节点的情况
{
ListNode<T>* current = get(pos); //找到要删除的节点
ListNode<T>* last = get(pos - 1); //找到要删除的节点的前一个节点
last->link = current->link;
delete current;
}
else
cout << "序号超出范围!" << endl;
}
else
cout << "序号不能为负数!" << endl;
}
}
//-----清空链表-----------------------------------------//
template <typename T>
void List<T>::clc()
{
int length = len();
for (int i = 0; i < length; i++)
del(0);
}