思想和上篇文章差不多,只是换了层包装。
直接上代码:
// linklist.h #include <iostream> #include <cstdio> using namespace std; template <typename T> struct Node { T t; Node<T> *next; }; template <typename T> class LinkList { public: LinkList(); ~LinkList(); public: int clear(); int insert(T &t, int pos); int get(int pos, T &t); int del(int pos, T &t); int getLen(); protected: Node<T> *header; int length; }; template <typename T> LinkList<T>::LinkList() { header = new Node < T > ; header->next = NULL; length = 0; } template <typename T> LinkList<T>::~LinkList() { Node<T> *tmp = NULL; while (header) { tmp = header->next; delete header; header = tmp; } } template <typename T> int LinkList<T>::clear() { ~LinkList(); LinkList(); return 0; } template <typename T> int LinkList<T>::insert(T &t, int pos) { Node<T> *cur = NULL; // 对pos的容错处理 if (pos >= length) { pos = length; } cur = header; for (int i = 0; i < pos; ++i) { cur = cur->next; } // 把上层应用的t结点缓存到容器中 Node<T> *node = new Node < T > ; node->next = NULL; node->t = t; // 把t缓存到容器中 node->next = cur->next; cur->next = node; ++length; return 0; } template <typename T> int LinkList<T>::get(int pos, T &t) { Node<T> *cur = NULL; if (pos >= length) { return -1; } cur = header; for (int i = 0; i < pos; ++i) { cur = cur->next; } t = cur->next->t; // 把pos位置的结点赋值给t return 0; } template <typename T> int LinkList<T>::del(int pos, T &t) { Node<T> *cur = NULL; if (pos >= length) { return -1; } cur = header; for (int i = 0; i < pos; ++i) { cur = cur->next; } Node<T> *ret = NULL; ret = cur->next; t = ret->t; // 把缓存的结点给上层应用t // 删除操作 cur->next = ret->next; --length; delete ret; // 注意释放内存,因为insert的时候new Node<T> return 0; } template <typename T> int LinkList<T>::getLen() { return length; }
#include <iostream> #include <cstdio> #include "linklist.h" using namespace std; struct Student { char name[32]; int age; }; void play() { Student s1, s2, s3; s1.age = 21; s2.age = 22; s3.age = 23; LinkList<Student> list; // 创建链表 // 插入元素 list.insert(s1, 0); list.insert(s2, 0); list.insert(s3, 0); // 遍历元素 Student tmp; for (int i = 0; i < list.getLen(); ++i) { list.get(i, tmp); cout << "age: " << tmp.age << endl; } // 删除元素 while (list.getLen()) { list.del(0, tmp); cout << "age: " << tmp.age << endl; } } int main() { play(); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zyq522376829/article/details/46845739