数据结构双链表实现

数据结构双链表实现

//参考李春葆数据结构双链表 
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

susuboom

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值