链表的抽象数据结构

      将作为类型的List(表)和Position(位置)以及函数的原型都列在  .h 头文件中。具体的Node(结点)声明则在 .c 文件中。

#idndef _List_H
    struct Node;
    typedef struct Node *PtrToNode;    //结构体指针
    typedef PtrToNode List;
    typedef PtrToNode Position;

    List MakeEmpty(List L);
    Int IsEmpty(List L);
    Int IsLast(List L);
    Position Find(ElementType x, List L);
    void Delete(ElementType x, List L);
    Position FindPrevious(ElementType x, List L);
    void Insert(List L);
    void DeleteList(List L);
    Position Header(List L);
    Position First(List L);
    Position Advance(Position P);
    ElementType Retrive(Position P);
#endif
struct Node
{
    ElementType Element;
    Position Next;
}
//是否为空
int IsEmpty(List L)
{
    return L->next==NULL;
}

//节点是否是尾节点
int IsLast(Position P, List L)
{
    return P->next==NULL;
}

//查找结点
Position Find(ElementType x,List L)
{
    Positon P;
    P=L-next;     //从表头后第一个节点开始
    while(P!=NULL && P->Element !=x)
        P=P->Next;
    return P
}
//删除节点
void Delete(ElementType x,List L)
{
    Position P, TmpCell;
    P=FindPrevious(x,L);
    if(!IsLast(P.L))
    {
        TmpCell=p->Next;
        p->Next=TmpCell->Next;
        free(TmpCell);
    }
}
//free(TmpCell)的结果是:TmpCell正在指向的地址没变,但在该地址处的数据此时已无定义了。

//查找节点的前驱
Position FindPrevious()
{
    Position P;
    P=L;           //从表头节点开始(统一性)
    while(P->next !=NULL && P->next->Element !=x)
        P=P->next;
    return P;
}

//插入节点
void Insert(ElementType x, List L, Position P)
{
    Position TmpCell;
    TmpCell=malloc(sizeof(struct Node)) //malloc返回的类型是 struct Node *
    if(TmpCell==NULL)    //对于malloc分配出来的单元都应检查是否分配上了
        FatalError("out of spaceccell!")
    TmpCell->Element=x;
    TmpCell->Next=P->Next;
    P->Next=TmpCell;
}

//对于要被放弃的单元,应该需要一个临时的变量,因为在撤出指针的工作结束后,你将不能在应用它
//删除链表
void DeleteList(List L)
{
    Positon P,Tmp;
    P=L->Next;
    L->Next=NULL;
    while(P!=NULL)
    {
        Tmp=P->Next
        free(p);
        p=Tmp;
    }
}

猜你喜欢

转载自blog.csdn.net/ma_chen_qq/article/details/77005875
今日推荐