#include <iostream>
using namespace std;
template<class T> struct ListNode
{
T data;
ListNode<T> *next;
};
template<class T> class List{
public:
List();
~List();
bool insertNode(T,int);
void deleteNode(int n);
int find(T t);
void empty();
bool print();
int getLength()
{
return length;
}
private:
ListNode<T> * first,* last;
int length;
};
template<class T>
void List<T>::empty()
{
ListNode<T> *p,*q;
p=first->next;
first->next=NULL;
while(p)
{
q=p;
p=p->next;
delete q;
}
length=0;
}
template<class T>
bool List<T>::insertNode(T t,int n)
{
ListNode<T> *p;
p=first;
int i=1;
while(p!=NULL&&i<n)
{
p=p->next;
i++;
}
if(p==NULL&&i!=n)
return false;
else
{
ListNode<T> *q;
q=new ListNode<T>;
q->data=t;
q->next=p->next;
p->next=q;
length++;
return true;
}
}
template<class T>
void List<T>::deleteNode(int n)
{
int i=1;
ListNode<T> *p,*q;
p=first;
while(p->next!=NULL&&i!=n)
{
p=p->next;
i++;
}
q=p->next;
cout<<"删除数据项为.... "<<q->data<<endl;
p->next=p->next->next;
length--;
delete q;
}
template<class T> bool List<T>::print()
{
ListNode<T> *p=first->next;
if(length==0)
return false;
else
{
cout<<"链表中有"<<length<<"项数据"<<endl;
while(p)
{
cout<<p->data<<"\t";
p=p->next;
}
cout<<endl;
return true;
}
}
template<class T>
int List<T>::find(T t)
{
ListNode<T> *p=first->next;
int i=1;
while(p&&p->data!=t)
{
p=p->next;
i++;
}
if(p)
return i;
else
return 0;
}
template<class T>
List<T>::~List()
{
ListNode<T> *p;
while(p = first)
{
first=first->next;
delete q;
}
}
template<class T>
inline List<T>::List()
{
ListNode<T> * node=new ListNode<T>;
node->next=NULL;
first=last=node;
length=0;
}
链表类模板
猜你喜欢
转载自blog.csdn.net/zhousw1999/article/details/79874500
今日推荐
周排行