双链表:
主要注意最后结点的操作,否则容易出现NULL->prior的情况。
#include <stdio.h>
#include <stdlib.h>
typedef struct DLNode
{
int data;
struct DLNode *prior;
struct DLNode *next;
}DLNode,*List;
//尾插法构建
void createndList(List &L,int a[], int n)
{
List f,l;
L=(List)malloc(sizeof(DLNode));
f=L;
int i;
for(i=0;i<n;i++)
{
l=(List)malloc(sizeof(DLNode));
l->data=a[i];
//尾插法
f->next=l;
l->prior=f;
f=l;
}
f->next=NULL;
}
void creatfirstList(List &L,int a[],int n)
{
L=(List)malloc(sizeof(DLNode));
List f,s;
f=L;
f->next=NULL;
int i;
for(i=0;i<n;i++)
{
s=(List)malloc(sizeof(DLNode));
s->data=a[i];
s->prior=f;
s->next=f->next;
f->next=s;
//最初的末指针是空,没前驱指针
if(i!=0)
f->next->next->prior=s;
}
}
//查找某元素值,返回位置
int find(List L,int x)
{
List s;
s=L->next;
int i=0;
while(s)
{
if(s->data==x)
return i;
s=s->next;
i++;
}
return -1;
}
//删除x
void deletelist(List &L,int x)
{
List s;
s=L->next;
while(s)
{
if(s->data==x)
{
if(s->next!=NULL)
{
s->next->prior=s->prior;
s->prior->next=s->next;
}
else
s->prior->next=NULL;
free(s);
}
s=s->next;
}
}
//输出
void pri(List L)
{
List s;
s=L->next;
while(s!=NULL)
{
printf("%d\n",s->data);
s=s->next;
}
}
//插入,根据位置x插入n
void insert(List &L,int x,int n)
{
List s,l;
l=L;
s=(List)malloc(sizeof(DLNode));
s->data=n;
int i;
for(i=0;i<=x-1;i++)
{
if(l->next==NULL)
{
printf("数据插入位置过大");
return;
}
l=l->next;
}
if(l->next!=NULL)
{
s->next=l->next;
s->prior=l;
l->next->prior=s;
l->next=s;
}
else
{
s->next=NULL;
l->next=s;
}
}
int main()
{
List L;
int a[5]={1,2,3,4,5};
creatfirstList(L, a, 5);
int x;
//x=find(L, 1);
//deletelist(L, 1);
insert(L, 1, 99);
//printf("%d",x);
pri(L);
return 0;
}

405

被折叠的 条评论
为什么被折叠?



