在单链表的每个结点中再设置一个指向其前驱结点的指针域,这样就形成了双链表,再将头结点和尾结点连接起来也就能构成循环双链表。
1.无论是插入还是删除操作,对链表中开始结点、终端节点和中间任意结点的操作过程相同。
2.设指针p指向循环双链表中的某一结点,则循环双链表具有如下对称性:(p->prior)->next=p=(p->next)->prior
代码:
#include<iostream>
using namespace std;
#define null 0
struct Node
{
int data;
Node *next,*prior;
};
class DoublyLinkList
{
private:
Node *first;
public:
DoublyLinkList();
DoublyLinkList(int a[],int n);
~DoublyLinkList();
int Length();
int Get(int i);
int Locate(int x);
void Insert(int i,int x);
int Delete(int i);
void PrintList();
};
DoublyLinkList::DoublyLinkList()
{
first=new Node;
first->next=first;
first->prior=first;
}
DoublyLinkList::DoublyLinkList(int a[],int n)
{
//头插法
first=new Node;
first->next=first;
first->prior=first;
for(int i=0;i<n;i++)
{
Node *s=new Node;
s->data=a[i];
s->prior=first;
s->next=first->next;
first->next->prior=s;
first->next=s;
}
}
DoublyLinkList::~DoublyLinkList()
{
Node *p=new Node;
Node *q=new Node;
p=first->next;
while(p!=first)
{
q=p->next;
delete p;
p=q;
}
}
int DoublyLinkList::Length()
{
int c=0;
Node *p=new Node;
p=first->next;
while(p!=first)
{
p=p->next;
c++;
}
return c;
}
int DoublyLinkList::Get(int i)
{
int c=1;
Node *p=new Node;
p=first->next;
while(p!=first && c<i)
{
p=p->next;
c++;
}
if(p==null) throw "位置";
else return p->data;
}
int DoublyLinkList::Locate(int x)
{
int c=1;
Node *p=new Node;
p=first->next;
while(p!=first)
{
if(p->data==x) return c;
else
{
p=p->next;
c++;
}
}
}
void DoublyLinkList::Insert(int i,int x)
{
int c=1;
Node *p=new Node;
p=first->next;
while(p!=first && c<i-1)
{
p=p->next;
c++;
}
Node *s=new Node;
s->data=x;
s->prior=p->prior;
p->prior=s;
s->next=p->next;
p->next=s;
}
int DoublyLinkList::Delete(int i)
{
Node *p=new Node;
p=first->next;
int c=1;
while(p!=first && c<i-1)
{
p=p->next;
c++;
}
if(p==first || p->next==first) throw "位置";
else
{
int x=p->next->data;
p->next=p->next->next;
p->next->next->prior=p;
delete p;
return x;
}
}
void DoublyLinkList::PrintList()
{
Node *p=new Node;
p=first->next;
while(p!=first)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
int a[10]={2,5,8,3,6,2,10,7,1,4};
DoublyLinkList ll(a,10);
ll.PrintList();
cout<<ll.Length()<<endl;
cout<<ll.Get(3)<<endl;
cout<<ll.Locate(10)<<endl;
ll.Insert(4,22);
ll.PrintList();
cout<<ll.Delete(4)<<endl;
ll.PrintList();
return 0;
}