您的位置:首页 > 其它

双向链表

2015-10-29 20:33 239 查看
单链表和单循环链表的结点中只设有一个指向其直接后继的指针域,因此,从某个结点出发只能顺着指针向后访问其他结点。若需要查找结点的直接前驱,则需要从头指针开始查找某结点的直接前驱结点。如若希望从表中快速确定一个结点的直接前驱,只要在单链表的结点类型中增加一个指向其直接前驱的指针域prior即可。这样形成的链表中有两条不同的方向的链,因此称为双向链表。

template<class T> class doublelinklist;

template<class T>class doublelistnode

{

public:
friend class doublelinklist<T>;/*友元类*/

private:
T data;
doublelistnode<T>*prior,*next;

};

template<class T>class doublelinklist

{

public:
doublelinklist();
~doublelinklist(){head->prior==head->next=NULL;}
bool listempty(){ return head->prior==head->next;}
int listlength();
bool getdata(int i,T &x);
doublelistnode<T>*locatedata(T x);
void insertnode(int i,T x);
void deletenode(int i,T &x);
void printlist();

private:
doublelistnode<T>*head;

};

/*定义构造函数*/

template<class T>doublelinklist<T>::doublelinklist()

{

  head=new doublelistnode<T>;

  head->prior=head->next=NULL;

  length=0;

}

/*在i结点之前插入新结点*/

template<class T>void doublelinklist<T>::insertnode(int i,T x)

{
doublelistnode<T>*p=head,*s;
s=new doublelistnode<T>;
s->data=x;
int j=0;
while(p&&j<i)
{

       j++;
  p=p->next;
}
s->prior=p->prior;
s->next=p;

    p->prior->next=s;
p->prior=s;
length++;

}

/*删除第i个结点,将值存在x中*/

template<class T>void doublelinklist<T>::deletenode(int i,T &x)

{
doublelistnode<T>*p=head,*s;
int j=0;
s=p;
while(p&&j<i)
{
s=p;
p=p->next;
j++;
}
x=s->data;
s->prior->next=s->next;
p->prior=s->prior;
delete s;
length--;

}

/*输出链表*/

template<class T>void doublelinklist<T>:: printlist()

{
doublelistnode<T>*p=head->next;
while(p!=head)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;

}

/*获取指定值的地址*/

template<class T>doublelistnode<T>* doublelinklist<T>::locatedata(T x)

{
doublelistnode<T>*p=head->next;
while(p!=head&&p->data=x)
{
p=p->next;}
return p;

}

/*获取第i个结点的值,并存在x中*/

template<class T>bool doublelinklist<T>:: getdata(int i,T &x)

{
if(i<0||i>length)
return false;
doublelistnode<T>*p=head,*s;
int j=0;
s=p;
while(p&&j<i)
{  
j++;
s=p;
p=p->next;
}
if(p)
{x=s->data;
return true;}
else
return false;

}

/*获取链表的长度*/

template<class T>int doublelinklist<T>:: listlength()

{
doublelistnode<T>*p=head->next;
int length=0;
while(p!=head)
{
length++;
p=p->next;
}
return length;

}

#include<iostream>

#include"doublelistnode.h"

using namespace std;

int main()

{
doublelinklist<int>DL;
doublelistnode<int>*p;
int k,j;
int d=0;
for(k=0,j=2;k<5;k++,j=j+2)
DL.insertnode(k,j);
DL.printlist();
p=DL.locatedata(8);
DL.deletenode(3,d);
cout<<"length="<<DL.listlength()<<endl;
DL.printlist();
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: