您的位置:首页 > 理论基础 > 数据结构算法

数据结构之双链表操作

2016-03-23 18:52 323 查看
/*
编写一个程序,实现双链表的各种基本运算(假设双链表的元素类型为Char)。
(1)初始化双链表h;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出双链表h;
(4)输出双链表h长度;
(5)判断双链表h是否为空;
(6)输出双链表h的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出双链表h;
(10)删除h的第3个元素;
(11)输出双链表h;
(12)释放双链表h。
*/

#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <cstring>
using namespace std;
typedef char ElemType;
typedef struct DNode
{
ElemType data;
struct DNode *prior;
struct DNode *next;
} DLinklist;

void InitList(DLinklist *&L)  //初始化双链表h
{
L=(DLinklist *)malloc(sizeof (DLinklist));
L->prior=L->next=NULL;
}
void CreateListR(DLinklist *&L,ElemType a[],int n)   //采用尾插法依次插入元素a,b,c,d,e
{
DLinklist *s,*r;
int i;
L=(DLinklist *)malloc(sizeof(DLinklist));
r=L;
for(i=0; i<n; i++)
{
s=(DLinklist *)malloc(sizeof(DLinklist));
s->data=a[i];
r->next=s;
s->prior=r;
r=s;
}
r->next=NULL;
}
void DispList(DLinklist *L)         //输出双链表h
{
DLinklist *p=L->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int ListLength(DLinklist *L)      //输出双链表h的长度
{
int n=0;
DLinklist *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return (n);
}
bool ListEmpty(DLinklist *L)      //判断双链表h是否为空
{
return(L->next==NULL);
}
void Disp3(DLinklist *L,int j)    //输出双链表h的第3个元素
{
DLinklist *p=L->next;
int i=1;
while(i<j&&p!=NULL)
{
i++;
p=p->next;
}
cout<<p->data<<endl;

}
void Displocation(DLinklist *L,ElemType a)  //输出元素a的位置
{
DLinklist *p=L->next;
int i=1;
while(p!=NULL)
{
if(p->data==a)
cout<<i<<" ";
p=p->next;
i++;
}
cout<<endl;
}
bool ListInsert(DLinklist *&L,int i,ElemType e)   //插入数据元素
{
int j;
DLinklist *p=L,*s;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
s=(DLinklist *)malloc(sizeof(DLinklist));
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(DLinklist *&L,int i)    //删除数据元素
{
int j=0;
DLinklist *p=L,*q;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=p->next;
if(q==NULL)
return false;
p->next=q->next;
if(p->next!=NULL)
p->next->prior=p;
free(q);
return true;
}
}
void DestoryList(DLinklist *&L)        //销毁双链表
{
DLinklist *p=L,*q=L->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(p);
}
int main()
{
char a[10];
char b='a';
gets(a);
DLinklist *L;
InitList(L);
CreateListR(L,a,strlen(a));
cout<<"输出双链表:";
DispList(L);
cout<<"双链表的长度:"<<ListLength(L)<<endl;
cout<<"双链表是否为空:";
if(ListEmpty(L))
cout<<"是"<<endl;
else
cout<<"否"<<endl;
cout<<"双链表L的第三个元素为:";
Disp3(L,3);
cout<<"输出元素"<<b<<"的位置:";
Displocation(L,b);
ListInsert(L,4,'f');
cout<<"已在第4个元素位置上插入元素f"<<endl;
cout<<"输出双链表:";
DispList(L);
ListDelete(L,3);
cout<<"已删除第3个位置上的元素"<<endl;
cout<<"输出双链表:";
DispList(L);
DestoryList(L);
cout<<"双链表已释放!"<<endl;
return 0;
}

运行结果:

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