文章标题

来源:互联网 发布:日在校园知乎 编辑:程序博客网 时间:2024/06/05 02:40

抽象数据类型(abstract data type)

是一些操作的集合。包括对 表,图,集合 的操作

对于集合ADT,有并,交,测定大小以及取余等操作。
这些操作的实现只在程序中编写一次,而程序中任何的其他部分需要在该ADT上运行其中的一种操作时可以通过适当的函数来进行。

表ADT实现

操作:查找(Find)、插入(Insert)、删除 (Delete)

链表实现

测试一个链表是否是空链表

/*Return true if L is empty*/intIsEmpty(List L){    return L->Next==NULL;}

测试当前位置是否是链表的末尾

/*Return true if P is the last position in list L*//*Parameter L is unused in this implementation*/int IsLast(Position P,List L){    return P->Next==NULL;}

Find 例程

//Return Position of X in L;NULL if not foundPosition Find(ElementType X,List L){    Position P;    P=L->Next;    while(P!=NULL&&P->Element !=X)        P=P->Next;    return P;}

Delete例程

/*Delete first occurrence of X from a list*//*Assume use of a header node*/void Delete(ElementType X,List L){    Position P,TmpCell;    P=FindPrevious(X,L);    if(!IsLast(L))/*Assumption of header use */    {        TmpCell=P->Next;//X is found ;delete it        P->Next=TmpCell->Next;//Bypass deleted cell        free(TmpCell);    }}

FindPrevious——为与Delete一起使用的Find例程

/*If X is not found;then Next filed of returned*//*Position is NULL*//*Assumes a header*/FindPrevious(ElementTYpe X,List L){    Position P;    P=L;    while(P->Next!=NULL&&P->Element!=x)        p=p->Next;    return P;}

Insert例程

Insert(Element X,List L,position P){    Position TmpCell;    TmpCell=malloc(sizeof(struct Node));    if(TmpCell==NULL)        FatalError("OUT OF SPACE!!!");    TmpCell->Element=x;    TmpCell->Next=P->Next;    P->Next=TmpCell;}

注意

我们把链表L传递给Insert例程和InLast例程,尽管没有被使
用,是因为别的实现方法可能有需要,若不传入可能导致使
用ADT失败。

常见错误P37

”memory access violation 或 segmentation violation”意味着有指针变量包含伪地址。
原因是 <1>初始化变量失败。<2>指针为空指针,指向非法。
第2种错误涉及何时使用malloc获得新单元。
申明指向一个结构的指针并不创建该结构,而只是给出足够空间容纳结构可能会使用的地址。
free(P):P指向的地址不变,该地址的数据已无定义。

删除表的方法

/*Correct Delete list algorithm*/void DeleteList(List L){    Position P,Tmp;    P=L->Next;    L->Next=NULL;    while(P)    {        Tmp=P->Next;        free(P);        P=Tmp;    }}
1 0
原创粉丝点击