数据结构与算法(3)--双向链表存储结构

双向链表存储结构

#include
#define Elemtype int
typedef struct DNode{
	Elemtype data;
	Struct DNode *prior,*next;
}DNode,*DLinkList; 

//初始化 (头插法)
DLinkList InitDLinkList(DLinkList &L)
{
	L = (DLinkList)malloc(sizeof(DNode));
	L->next = NULL;
	L->prior = NULL;
	Elemtype x;
	DNode *p,*q;
	q = L->next; //q指向第一个元素 
	scanf("%d",&x);
	while(x!=9999)
	{
		p = (DNode*)malloc(sizeof(DNode));
		p->data = x;
		p->next = q;
		p->prior = L;
		L->next = p; 
		q = p;
	}
	return L; 
} 

//初始化 尾插法
DLinkList InitDLinkList(LinkList &L)
{
	L = (DLinkList)malloc(sizeof(DNode));
	L->next = NULL;
	L->prior = NULL;
	DNode *q,*p; 
	scanf("%d",&x);
	q = L;
	while(x != 9999)
	{
		p = (DNode*)malloc(sizeof(DNode));
		p->next = NULL;
		p->data = x;
		p->prior = q;
		q->next = p;
		q = p;
	}
	return L;
}

//在第i个位置插入元素
bool InsertDLinkList(DLinkList &L,Elemtype e,int i)
{
	if(i<=0)
	{
		return false;
	}
	DNode *p,*q;
	p = L->next; 
	for(int j = 1;j<i;j++) 
	{
		if(!p)
		{
			return false; 
		} 
		p = p->next;
		j++;
	}
	q = (DNode*)malloc(sizeof(DNode));
	p->next = q;
	q->prior = p;
	q->next = p->next->next;
	p->next->next->prior = q; 
	return false;
} 

//删除第i个位置元素
bool DeleteDLinkList(DLinkList &L,int i,Elemtype &e)
{
	if(i<=0)
	{
		return false;
	}
	DNode *p,*q;
	p = L->next;
	for(int j=1;j<i;j++)
	{
		if(!p)
		{
			return false;
		}
		j++;
		p = p->next;
	}
	q = p->next;
	e = q->data;
	p->next = q->next;
	q->next->prior = p;
	free(q);
	return true;
} 

 


你可能感兴趣的:(数据结构)