单链表的建立
#include <iostream>
using namespace std;
template<class DateType>
struct Node
{
DateType date;
Node<DateType> *next;
};
template<class DateType>
class LinkList
{
public:
LinkList();
LinkList(DateType a[],int n);
~LinkList();
int Length();
DateType Get(int i);
int Locate(DateType x);
void Insert(int i,DateType x);
DateType Delete(int i);
void PrintList();
private:
Node<DateType>*first;
};
template<class DateType>
void LinkList<DateType>::PrintList()
{
Node<DateType> *p;
p=first->next;
while(p!=NULL){
cout<<p->date<<" ";
p=p->next;
}
cout<<endl;
}
template<class DateType>
int LinkList<DateType>::Length()
{
Node<DateType> *p;
int length=0;
p=first->next;
while(p!=NULL){
length++;
p=p->next;
}
return length;
}
template<class DateType>
DateType LinkList<DateType>::Get(int i)
{
Node<DateType> *p;
int cnt=1;
p=first->next;
while(p!=NULL&&cnt<i){
p=p->next;
cnt++;
}
if(p==NULL) throw"位置";
else return p->date;
}
template<class DateType>
int LinkList<DateType>::Locate(DateType x)
{
Node<DateType> *p;
int cnt=1;
p=first->next;
while(p!=NULL){
if(p->date==x)
return cnt;
p=p->next;
cnt++;
}
return 0;
}
template<class DateType>
void LinkList<DateType>::Insert(int i,DateType x)
{
Node<DateType> *p;
p=first;
int cnt=1;
while(p!=NULL&&cnt<i){
p=p->next;
cnt++;
}
if(p==NULL) throw"位置";
else{
Node<DateType> *q;
q=new Node<DateType>;
q->date=x;
q->next=p->next;
p->next=q;
}
}
template<class DateType>
LinkList<DateType>::LinkList()
{
first=new Node<DateType>;
first->next=NULL;
}
//头插法
template<class DateType>
LinkList<DateType>::LinkList(DateType a[],int n)
{
first=new Node<DateType>;
first->next=NULL;
Node<DateType> *s;
for(int i=0;i<n;i++)
{
s=new Node<DateType>;
s->date=a[i];
s->next=first->next;
first->next=s;
}
}
/*
//尾插法
template<class DateType>
LinkList<DateType>::LinkList(DateType a[],int n)
{
first=new first;
Node<DateType> *s,*r;
r=first;
for(int i=0;i<n;i++)
{
s=new Node;
s->date=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
*/
template<class DateType>
DateType LinkList<DateType>::Delete(int i)
{
Node<DateType> *p,*q;
DateType x;
p=first;
int cnt=1;
while(p!=NULL&&cnt<i){
p=p->next;
cnt++;
}
if(p==NULL||p->next==NULL) throw"位置";
else{
q=p->next;
x=q->date;
p->next=q->next;
delete q;
return x;
}
}
template<class DateType>
LinkList<DateType>::~LinkList()
{
Node<DateType> *s;
while(first!=NULL)
{
s=first;
first=first->next;
delete s;
}
}
int main()
{
int a[]={0,9,8,7,6,5,4,3,2,1};
LinkList<int>l(a,10);
cout<<l.Length()<<endl;
cout<<"第3个节点的元素是:"<<l.Get(3)<<endl;
cout<<"值为5的元素的节点:"<<l.Locate(5)<<endl;
l.Insert(3,5);//第三个节点插入5
cout<<"删除第8个节点的元素;"<<l.Delete(8)<<endl;
l.PrintList();
return 0;
}
注意在主函数中定义链表时一定要说明数据类型,另外在成员函数中申请空间时也要说明数据类型。