单向链表的常用操作(C++模板实现)
来源:互联网 发布:域名第四级地址 编辑:程序博客网 时间:2024/05/16 04:43
最近担任我们学校C++课程的助教,发现这群98年左右的小孩编程能力实在是差,一个链表操作都能一个下午花去实现。话说,百度排前面的那些链表操作的代码写得也太不规范了吧。。。这里贴出一些上机实验时候关于链表操作的代码,希望那些孩子能百度到吧。。。
1,结构体
template <typename Object>struct Node{ Object data; Node* next; Node(const Object&d = Object(), Node*n = NULL) :data(d), next(n){}};
2,通过一个类实现
class singleList{public: singleList(){ inti(); } ~singleList(){ eraseList(head); } singleList(const singleList & rhs) { eraseList(head); init(); *this = rhs; } bool add(Object x) { if (contains(x))return false; else { Node<Object>*ptr = new Node<Object>(x); ptr->next = head->next; head->next = ptr; theSize++; } return true; } bool addSort(Object x)//有序添加 { if (contains(x))return false; else { Node<Object>*ptr = head->next; Node<Object>*trailer = head; while (ptr&&ptr->data < x) { trailer = ptr; ptr = ptr->next; } trailer->next = new Node<Object>(x); trailer->next->next = ptr; theSize++; } return true; } bool remove(Object x) { if (!contains(x))return false; else { Node<Object>*ptr = head->next; Node<Object>*trailer; while (ptr->data != x) { trailer = ptr; ptr = ptr->next; } trailer->next = ptr->next; delete ptr; theSize--; } return true; } int size(){ return theSize; } void print() { Node<Object>*ptr = head->next; while (ptr != NULL) { printf("%d ", ptr->data); ptr = ptr->next; } printf("\n"); } bool contains(const Object & x) { Node<Object>*ptr = head->next; while (ptr != NULL) { if (x == ptr->data) return true; else ptr = ptr->next; } return false; } void init() { theSize = 0; //Dwayne head = new Node < Object > ; head->next = NULL; } void eraseList(Node<Object>*h) { Node<Object>*ptr = h; Node<Object>*nextPtr; while (ptr != NULL) { nextPtr = ptr->next; delete ptr; ptr = nextPtr; } }private: Node<Object>*head; int theSize;};
原理没什么好说的,我博客里有一篇详细的分析,当然网上比我分析好的一大堆。我以后上课的时候把我博客的链接告诉那些孩子,这样也省了不少事情。
编程这事开始的时候效率先不提,最重要的是规范啊。多看大公司开源放出来的那些代码,模仿着去写。CSDN上也有不少人写得一手漂亮的代码,但是林子大了什么鸟都有了。
0 0
- 单向链表的常用操作(C++模板实现)
- C++:操作单向链表的实现
- java实现单向链表的常用操作
- java实现单向链表的常用操作
- 单向链表的C语言实现与基本操作
- C++模板实现的单向链表
- C-单向链表的基本操作
- 实现单向链表的有关操作
- C++,数据结构,单向链表的实现及简单运用,运用模板
- 链表常用操作的实现-C++模板实现
- C语言单向链表的实现
- C语言实现的单向链表
- 单向链表的C语言实现
- C语言单向链表的实现
- c语言单向链表的实现
- C语言单向链表的实现
- C语言单向链表的实现
- C语言单向链表的实现
- ORA-01092: ORACLE instance terminated. Disconnection forced
- Java访问权限修饰词
- burp-intrude-Attack-type的使用介绍
- 【cdoj 1380】 Xiper的奇妙历险(3) bfs+逆向思维 有质量的bfs
- CSDN编辑器用法--自用
- 单向链表的常用操作(C++模板实现)
- Linux+树莓派3开发总结——开源堡垒机Gate One的安装、配置笔记(远程web访问)
- js学习笔记(七)onfocus事件和blur的使用
- 【MySql】 BlackHole :黑洞引擎
- 周期串
- 欢迎使用CSDN-markdown编辑器
- 郁闷的C小加(一)
- SharedPreferences工具类
- mysql必知