数据结构自学之路---单链表
2016-06-06 00:24
183 查看
#include <iostream> using namespace std; template<typename T> class Node; //单链表的定义 template<typename T> class List { private: Node<T> *head; public: List(){ head=new Node<T>(); } ~List(){ delete head; } bool insert(int i,T data); //插入元素 T getnodedata(int i); //获取指定元素 void clean(); //清除链表 int getlength(); //获取链表长度 bool deletenode(Node<T> *p); //删除指定链表内容 }; //链表结点的定义 template<typename T> class Node { private: Node<T> *next; T data; public: Node(){ next=NULL; } Node(T item,Node<T> *newnext=0){ next=newnext; data=item; } ~Node(){ next=NULL; } T getdata(){ return data; } friend class List<T>; }; //插入元素的实现 template<typename T> bool List<T>::insert(int i,T data){ Node<T> *p=head; int j; for (j=1;j<=i-1;j++) { p=p->next; if (p==NULL) { break; } } if (p==NULL&&j<i-1) { return false; }else{ Node<T> *node=new Node<T>(data); node->next=p->next; p->next=node; return true; } } //获取指定下标的数据的实现 template<typename T> T List<T>::getnodedata(int i){ Node<T> *p=head->next; int j; for (j=1;j<=i-1;j++) { p=p->next; } return p->getdata(); } //获取链表的长度 template<typename T> int List<T>::getlength(){ int counter=0; Node<T> *p=head->next; while (p!=NULL) { p=p->next; counter++; } return counter; } //删除指定的链表元素 template<typename T> bool List<T>::deletenode(Node<T> *p){ Node<T> *node=head; if (p==NULL) { return false; }else{ while (node->next!=p) { node=node->next; } node->next=p->next; delete p; return true; } } //清除链表的元素 template<typename T> void List<T>::clean(){ Node<T> *p=NULL; while (p->next!=NULL) { p=head->next; head->next=p->next; delete p; } } void main() { List<int> list; for (int i=0;i<10;i++) { list.insert(i,i*10); cout<<list.getnodedata(i)<<" "; } cout<<endl; cout<<list.getlength()<<endl; list.clean(); cout<<endl; }
相关文章推荐
- 数据结构之数组
- 数据结构之数组
- 数据结构之数组
- 线性表--链式描述(一)
- 数据结构之2-3-4树
- 数据结构之2-3-4树
- 数据结构之2-3-4树
- redis数据结构之dict 概要
- 常用树类数据结构总结-二叉查找树(BST),平衡二叉查找树(AVL),红黑树(RBT),B~/B+树(B-tree)的性能分析
- 1.数据结构--线性表之数组实现
- 3.数据结构--线性表之一元多项式的加法与乘法运算
- Redis部分数据结构方法小结
- Redis中5种数据结构的使用场景介绍
- C 链式栈
- Java数据结构源码分析-Vector
- C单链表
- Java 数据结构之队列
- Java数据结构源码分析-LinkedList
- 数据结构之poj2388
- list_head数据结构分析