一、单链表

#define  ElementType int
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, Position P);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Tail(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);        //好多函数用不到

struct Node
{
    ElementType Element;
    Position next;
};

#include "linkedlist.h"
#include <stdio.h>
#include <stdlib.h>
List MakeEmpty(List L)
{

    L = (List)malloc(sizeof(struct Node));
    if (L == NULL)
    {
      perror("malloc error\n");
    }
    L->Element = 0;        //目前没找到更好的方法来设置开头的点,以后看到了再改动
    L->next = NULL;
    return L;

}

int IsEmpty(List L)
{
    return L->next == NULL;
}

int IsLast(Position P, List L)
{
    return P->next == NULL;
}

Position Find(ElementType X, List L)
{
//     while (L->next != NULL)
//     {
//         if (L->Element == X)
//             return L;
//         else
//             L = L->next;
//     }
    Position P;

    P = L->next;
    while (P != NULL && P->Element != X)
    {
        P = P->next;
    }
    return P;
}

Position FindPrevious(ElementType X, List L)
{
    Position P = L;
    while (P->next != NULL && P->next->Element != X)
        P = P->next;
    return P;
}

void Delete(ElementType X, List L)
{
//     Position P = FindPrevious(X, L);
//     Position temp = P->next;
//     if (P->next->next == NULL)
//     {
//         free(temp);
//         P->next = NULL;
//     }
//     else
//     {
//         P->next = temp->next;
//         free(temp);
//     }
    Position P, TmpCell;
    P = FindPrevious(X, L);
    if ( !IsLast(P, L))        //如果是P最后一个,则说明X根本不存在,也就不用删除了
    {
        TmpCell = P->next;
        P->next = TmpCell->next;
        free(TmpCell);
    }
}

void Insert(ElementType X, List L, Position P)
{
    Position tmp = (Position)malloc(sizeof(struct Node));
    if (tmp == NULL)
    {
        perror("malloc error\n");
    }
    tmp->Element = X;
    tmp->next = P->next;
    P->next = tmp;

}

void DeleteList(List L)
{
    Position P = L->next;
    Position tmp = P;
    while (P != NULL)
    {
        P = P->next;
        free(tmp);
        tmp = P;
    }
}

Position Header(List L)
{
    return (Position)L;
}

Position First(List L)
{
    Position P = L->next;
    return P;
}

Position Advance(Position P)
{
    return P->next;
}

ElementType Retrieve(Position P)
{
    return P->Element;
}

Position Tail(List L)
{
    Position P = L;
    while (P->next != NULL)
        P = P->next;
    return P;
}
posted @ 2015-09-23 21:54  dylqt  阅读(156)  评论(0编辑  收藏  举报