测试代码
#include <iostream>
#include <iomanip>
using namespace std;
template <class DataType>
struct DulNode
{
DataType data;
DulNode <DataType>*prior,*next;
};
template <class DataType>
class DoubleList
{
public:
DoubleList(DataType a[],int n);
void Insert(int i,DataType x);
DataType Delete (int i);
void PrintList();
private:
DulNode<DataType> *first;
};
template <class DataType>
DoubleList<DataType>::DoubleList(DataType a[],int n)
{
DulNode<DataType> *r;
DulNode<DataType> *s;
first=new DulNode<DataType>;
r=first;
for(int i=0;i<n;++i)
{
s=new DulNode<DataType>;
s->data=a[i];
s->prior=r;
s->next=r->next;
r->next=s;
r=s;
}
cout<<"ok"<<endl;
}
template <class DataType>
void DoubleList<DataType>::Insert(int i,DataType x)
{
DulNode<int>*p;
DulNode<int>*s;
p=first;
int count=1;
while(p!=NULL||count<i)
{
p=p->next;
count++;
}
if(p==NULL)
throw"位置";
else{
s=new DulNode;
s->data=int x;
p->prior->next=s;
s->prior=p->prior;
p->prior=s;
s->next=p;
}
}
template <class DataType>
DataType DoubleList<DataType>::Delete(int i)
{
DulNode<int>*p;
p=first->next;
int count=1;
while(p!=NULL||count<i)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)
throw"位置";
else
{
int x=p->data;
(p->prior)->next=p->next;
(p->next)->prior=p->prior;
delete p;
return x;
}
}
template <class DataType>
void DoubleList<DataType>::PrintList()
{
DulNode<int>*p;
p=first->next;
while(p!=NULL)
{
cout<<setw(2)<<p->data;
p=p->next;
}
}
int main()
{
int b[5]={1,2,3,4,5};
DoubleList<int> L(b,5);
cout<<"双链表创建完成"<<endl;
L.PrintList();
return 0;
}
测试结果