数据结构双链表实现
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElemType;
typedef struct DNode
{
ElemType data;
struct DNode *prior;
struct DNode *next;
}DLinkNode;
void CreateListF(DLinkNode *&L,ElemType a[],int n)
{
DLinkNode *s;
L=(DLinkNode *)malloc(sizeof(DLinkNode));
L->prior=L->next=NULL;
for(int i=0;i<n;i++)
{
s=(DLinkNode*)malloc(sizeof(DLinkNode));
s->data=a[i];
s->next=L->next;
if(L->next!=NULL)L->next->prior=s;
L->next=s;
s->prior=L;
}
}
void CreateListR(DLinkNode *&L,ElemType a[],int n)
{
DLinkNode *s,*r;
L=(DLinkNode *)malloc(sizeof(DLinkNode));
r=L;
for(int i=0;i<n;i++)
{
s=(DLinkNode*)malloc(sizeof(DLinkNode));
s->data=a[i];
r->next=s;
s->prior=r;
r=s;
}
r->next=NULL;
}
void DispList(DLinkNode *L)
{
DLinkNode *p=L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void DestroyList(DLinkNode *&L)
{
DLinkNode *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
free(pre);
}
bool ListInsert(DLinkNode *&L,int i,ElemType e)
{
int j=0;
DLinkNode *p=L,*s;
if(i<=0)return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)return false;
else
{
s=(DLinkNode *)malloc(sizeof(DLinkNode));
s->data=e;
s->next=p->next;
if(p->next!=NULL)p->next->prior=s;
p->next=s;
s->prior=p;
return true;
}
}
bool ListDelete(DLinkNode *&L,int i,ElemType &e)
{
int j=0;
DLinkNode *p=L,*q;
if(i<=0)return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)return false;
else
{
q=p->next;
if(q==NULL)return false;
e=q->data;
p->next=q->next;
if(p->next!=NULL)p->next->prior=q;
free(q);
return true;
}
}
int main()
{
ElemType e;
int a[]={1,2,3,33,8,6,9,76,154,67};
DLinkNode *L;
CreateListR(L,a,10);
DispList(L);
ListInsert(L,3,5);
DispList(L);
ListDelete(L,5,e);
DispList(L);
DestroyList(L);
return 0;
}