测试代码
#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);//插入操作,在第i个位置插入元素x
DataType Delete (int i);//删除第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;
// cout<<"sda"<<endl;
r->next=s;
//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)//删除第i个元素
{
DulNode<int>*p;
//Node<int>*first;
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;
//Node<int>*first;
p=first->next;
while(p!=NULL)
{
cout<<setw(2)<<p->data;
p=p->next;
}
}
int main()
{
//cout<<"请输入五位数字:"<<endl;
int b[5]={1,2,3,4,5};
DoubleList<int> L(b,5);
cout<<"双链表创建完成"<<endl;
L.PrintList();
return 0;
}
测试结果