算法:单链表实现

list.h

#ifndef _LIST_H_
#define _LIST_H_

struct Node;
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

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

#endif

struct Node
{
    ElementType element;
    Position Next;
};

list.c

#include "list.h"
#include <stdlib.h>
#include <stdio.h>

List MakeList(List L)
{
    Position P,temp;
    P=L->Next;
    while(P!=NULL){
        temp=P;
        P=P->Next;
        free(temp);
    }
    return L;
}
int IsEmpty(List L)
{
    return L->Next==NULL;
}
Position Find(ElementType X,List L)
{
    Position P;
    P=L->Next;
    L->Next=NULL;
    while(P!=NULL&&P->element!=X){
        P=P->Next;
    }
    return P;
}
Position FindPrevious(ElementType X,List L)
{
    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 temp;
    temp=malloc(sizeof(struct Node));
    if(temp==NULL){
        printf("out of space");
        exit(1);
    }
    temp->element=X;
    temp->Next=P->Next;
    P->Next=temp;
}
void Delete(ElementType X,List L)
{
    Position P,temp;
    P=FindPrevious(X,L);
    if(P->Next!=NULL){
        temp=P->Next;
        P->Next=temp->Next;
        free(temp);
    }
}
void DeleteList(List L)
{
    MakeEmpty(L);
}

 

posted @ 2017-03-06 22:15  jmst  阅读(182)  评论(0编辑  收藏  举报