数据结构自学之路---单链表

来源:互联网 发布:蓝海文交软件下载 编辑:程序博客网 时间: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
原创粉丝点击