您的位置:首页 > 编程语言 > C语言/C++

链表ADT C语言实现

2016-02-11 21:52 405 查看
代码的规范与编程风格的一致是非常重要的。

下列代码C语言风格的代码。

代码的风格是 Mark Allen weiss 所著的 数据结构与算法分析----C语言描述上的。

这里的链表是带有表头的单链表。通过添加表头可以让代码清晰。

#ifndef _List_H
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

List MakeEmpty(List L);
int IsEmpty(List L);
int IsLast(Position P,list L);
Position Find(ElementType X,List L);
void Delete(ElementType X,List L);
Position FindPrevious(ElementType X,List L);
void Insert(ElementType X,List L);
void DeleteList(List L);

#endif


/*place in the implementation file*/
struct Node
{
    ElementType Element;
    Position Next;
};
/*return true if L is empty,判断链表是否为空*/
int IsEmpty(List L)
{
    return P->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;
}
/*return Position of X in L;NULL if not found*/
/*find例程*/
Position Find(ElementType X,List L)
{
    Position P;
    P=L->Next;
    
    while(P!=NULL&&P->Element!=X)
        P=P->Next;
        
    return P;
}
/*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(P,L))
    {
        TmpCell=P->Next;
        p->Next=TmpCell->Next;
        free(TmpCell);
    }
}
/*if x is not found , then next field of returned*/
/*position is NULL*/
/*Assume a header*/
/*Findprevious例程*/
Position FindPrevious(ElementType X,List L)
{
    Position P;
    
    P=L;
    while(P->Next!=NULL&&P->Next->Element!=X)
    {
        P=P->Next;
    }
    return P;
}
/*insert(after legal position)*/
/*Header implemtentation assumed*/
/*parameter L is unused in this implementation*/
/*链表的插入例程*/
void Insert(ElementType X,List L)
{
    Position TmpCell;
    TmpCell=malloc(sizeof(struct Node));
    if(TmpCell==NULL)
    {
        fprintf(stderr,"out of space");
        error(1);
    }
    TmpCell->Element=X;
    TmpCell->Next=P->Next;
    p->Next=TmpCell;
}
/*删除表*/
void DeleteList(List L)
{
    Position P,Tmp;
    
    P=L->Next;/*header assumed*/
    L->Next=NULL;
    while(P!=NULL)
    {
        Tmp=P->Next;
        free(P);
        P=Tmp;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: