Loading... 简单的实现了增删元素、输出链表元素和大小的功能 <!--more--> ```cpp #include <vector> #include <string> #include <iostream> #include <cstdlib> using std::string; template <class T> class List { private: struct listNode { listNode *next; T val; listNode(T val, listNode* next = nullptr) : val(val), next(next) {}; }; listNode* head; int size; public: List() : head(nullptr), size(0) {} void add(T); void print(); int getSize(){return size;}; void remove(T const&); }; template <class T> void List<T>::add(T elem) { if(head == nullptr) head = new listNode(elem); else { listNode* cur = head; while(cur->next != nullptr) cur = cur->next; cur->next = new listNode(elem); } ++size; } template <class T> void List<T>::remove(T const& elem) { if(head == nullptr) { std::cout << "链表为空!" << std::endl; return; } if(head->val == elem) { head = head->next; --size; return; } listNode* cur = head; while(cur->next && cur->next->val != elem) cur = cur->next; if(cur->next == nullptr) { std::cout << elem << "不在链表内!" << std::endl; return; } cur->next = cur->next->next; --size; return; } template <class T> void List<T>::print() { if(head == nullptr) { std::cout << "链表为空!" << std::endl; return; } listNode* cur = head; while(cur != nullptr) { std::cout << cur->val << " -> "; cur = cur->next; } std::cout << std::endl; } int main() { List<string> a; a.add("def"); a.add("abc"); a.add("anbd"); std::cout << "链表的长度为:" << a.getSize() << std::endl; a.remove("defa"); a.print(); return 0; } ``` Last modification:January 2, 2023 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 0 如果觉得我的文章对你有用,请随意赞赏