双链表实现

数据结构与算法分析——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;
}






你可能感兴趣的:(双链表实现)