数据结构自学之路---单链表
来源:互联网 发布:蓝海文交软件下载 编辑:程序博客网 时间:2024/06/08 11:05
#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;}
0 0
- 数据结构自学之路---单链表
- 数据结构自学之路----顺序表
- 自学之路
- 自学java之路
- 自学JAVA之路`~
- JAVA自学之路
- JAVA自学之路
- JAVA自学之路
- JAVA自学之路
- JAVA自学之路
- JAVA自学之路
- Java自学之路
- Linux自学之路
- Java自学之路
- java自学之路----
- JAVA自学之路
- delphi自学之路
- java自学之路
- 自定义view实现水波纹效果
- c++作业7
- hibernate使用带有sum()的hql语句出错的问题
- 总结几个实用的js/jq代码片段
- EasyCamera配置文件
- 数据结构自学之路---单链表
- c++上机第七次实验
- C++第7次上机实验
- STM32实现Pixhawk PPM
- c++作业7t
- C++上机作业7
- php curl开启方法
- c++第七次作业
- lightoj 1004 - Monkey Banana Problem