双链表实现

数据结构与算法分析——c语言描述 第三章的双链表

和单链表差不多,删除插入画个图就很形象了。


double_list.h

typedef int ElementType;
#ifndef _double_List_H  
#define _double_List_H  

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode DoubleList;
typedef PtrToNode Position;

DoubleList CreatList();
DoubleList MakeEmpty(DoubleList L);
int IsEmpty(DoubleList L);
int IsLast(Position P);
Position Find(ElementType X, DoubleList L);
void Delete_ElementType(ElementType X, DoubleList L);
void Delete_Position(Position p);
void Insert(ElementType X, Position P);
void DeleteList(DoubleList L);
Position Header(DoubleList L);
Position First(DoubleList L);
Position Advance(Position P);
Position Retreat(Position P);
ElementType Retrieve(Position P);

#endif  




double_list.c

#include"doubleList.h" 
#include<stdlib.h>  
#include"fatal.h"  

struct  Node
{
	ElementType Element;
	Position Next;
	Position Prev;
};

DoubleList CreatList() {
	DoubleList l = malloc(sizeof(struct Node));
	l->Prev = NULL;
	l->Next = NULL;
	return l;
}

DoubleList MakeEmpty(DoubleList L) {
	if (L != NULL)
		DeleteList(L);
	L = malloc(sizeof(struct Node));
	if (L == NULL)
		FatalError("Out of memory");
	L->Next = NULL;
	L->Prev = NULL;
	return L;
}

int IsEmpty(DoubleList L) {
	return L->Next == NULL;
}

int IsLast(Position P) {
	return P->Next == NULL;
}

Position Find(ElementType X, DoubleList L) {
	Position P;
	P = L->Next;
	while (P != NULL&&P->Element != X)
	{
		P = P->Next;
	}
	return P;
}

void Delete_ElementType(ElementType X, DoubleList L) {
	Position P;
	P = Find(X, L);
	Delete_Position(P);
}

void Delete_Position(Position p) {
	if (p != NULL) {
		Position last, next;
		last = p->Prev;
		next = p->Next;
		last->Next = next;
		if (!IsLast(p)) {
			next->Prev = last;
		}
		free(p);
	}
}

void Insert(ElementType X,  Position P) {
	Position tmpCell;
	tmpCell = malloc(sizeof(struct Node));
	if (tmpCell == NULL)
		FatalError("Out of space!!");
	Position temp = P->Next;
	P->Next = tmpCell;
	tmpCell->Next = temp;
	tmpCell->Prev = P;
	tmpCell->Element = X;
	if (temp != NULL) {
		temp->Prev = tmpCell;
	}
}

void DeleteList(DoubleList L) {
	Position p;
	p = L->Next;
	L->Next = NULL;
	while (p != NULL) {
		Position tmp;
		tmp = p->Next;
		free(p);
		p = tmp;
	}
}

Position Header(DoubleList L) {
	return L;
}

Position First(DoubleList L) {
	return L->Next;
}

Position Advance(Position P) {
	return P->Next;
}

Position Retreat(Position P) {
	return P->Prev;
}

ElementType Retrieve(Position P) {
	return P->Element;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值