From 3d10283acdb40dce5d3c3a789a872a6b3fee77fc Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sat, 23 Mar 2024 13:43:59 +0800 Subject: [PATCH] Add List.hpp --- List.hpp | 108 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 List.hpp diff --git a/List.hpp b/List.hpp new file mode 100644 index 0000000..598d4de --- /dev/null +++ b/List.hpp @@ -0,0 +1,108 @@ +#ifndef LIST_HPP +#define LIST_HPP + +#include +#include "Node.hpp" + +// 这里列举了链表类模板的最基本功能,对原教材当中的写法进行了修订 +// 更多功能改进,见对应的实战练习 + +template +class List +{ + Node *head, *tail; // 链表头指针和尾指针 +public: + List(); // 只生成头结点 + ~List(); // 删除整个链表 + void clear(); // 清空链表,只余表头结点 + Node *find(const T &data) const; // 返回数值为data的节点 + int length() const; // 计算单链表长度 + void print() const; // 打印链表的数据域 + void insert_front(Node *p); // 表头插入 + void insert_rear(Node *p); // 表尾插入 + Node *delete_node(Node *p); // 删除并返回地址为p的节点 +}; + +template +List::List() +{ + // 当链表为空时,tail指向头节点,否则指向链表最后一个节点 + head = tail = new Node{}; +} + +template +List::~List() +{ + clear(); + delete head; +} + +template +void List::clear() +{ + while (head->link) + head->RemoveAfter(); + tail = head; // 务必注意本类当中的操作是否会影响tail +} + +template +Node *List::find(const T &data) const +{ + Node *tempP{head->link}; + while (tempP && tempP->info != data) + tempP = tempP->link; + return tempP; // 搜索成功返回指点节点的指针,不成功返回nullptr +} + +template +int List::length() const +{ + int count{0}; + Node *tempP{head->link}; + while (tempP) + { + tempP = tempP->link; + ++count; + } + return count; +} + +template +void List::print() const +{ + Node *tempP{head->link}; + while (tempP) + { + tempP->print(); + tempP = tempP->link; + } + std::cout << '\n'; +} + +template +void List::insert_front(Node *p) +{ + head->InsertAfter(p); + if (tail == head) + tail = p; // 注意可能修正tail +} + +template +void List::insert_rear(Node *p) +{ + tail->InsertAfter(p); + tail = p; +} + +template +Node *List::delete_node(Node *p) +{ + Node *tempP{head}; // 注意与之前的不同 + while (tempP->link && tempP->link != p) // 找到p的位置 + tempP = tempP->link; + if (p == tail) + tail = tempP; // 修正tail + return tempP->RemoveAfter(); +} + +#endif \ No newline at end of file