单链表的C语言简单实现

单链表的C语言简单实现,参考《数据结构与算法分析—C语言描述》

#ifndef _List_h
#define _List_h
struct Node;
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

List CreatListHead(int N);
List MakeEmpty(List L);
int IsEmpty(List L);
int IsLast(Position P, List L);
Position Find(ElementType X, List L);
Position FindPrevious(ElementType X, List L);
void Delete(ElementType X, List L);
void Insert(ElementType X, int index, List L);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);
void PrintList(List L, int N);


#endif // _List_h


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

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)
{
    Position P;
    P = L->Next;

    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 Delete(ElementType X, List L)
{
    Position P, tmp;

	P = FindPrevious(X, L);
    if(!IsLast(P,L))
    {
        tmp = P->Next;
        P->Next = tmp->Next;
        free(tmp);
    }
}



void Insert(ElementType X, int index, List L)
{
    Position tmp;
	Position P;
	int count = 1;


	P = L->Next;
	while (P && count < index - 1)
	{
		P = P->Next;
		count++;
	}

    tmp = malloc(sizeof(struct Node));
    if(tmp == NULL)
        printf("out of space\n");

    tmp->Element = X;
    tmp->Next    = P->Next;
    P->Next      = tmp;
}
void DeleteList(List L)
{
    Position P,Tmp;

    P = L->Next;
    L->Next = NULL;

    while(P != NULL)
    {
        Tmp = P->Next;
        free(P);
        P = Tmp;
    }
}
/* 产生N个元素的值,建立带表头结点的单链线性表L(头插法)*/
List CreatListHead(int N)
{
    Position P;
    int i;
    //srand(time(0));
    List L = (List) malloc(sizeof(struct Node));
    L->Next = NULL;
    for(i = 0; i < N; i++)
    {
        P = (Position)malloc(sizeof(struct Node));
        P->Element = i + 1;
        P->Next = L->Next;
        L->Next = P;
    }

	return L;
}

void PrintList(List L, int N)
{
    int i;
    Position P = L->Next;

    for(i = 0; i < N; i ++)
    {
        printf("%d ",P->Element);
        P = P->Next;
    }
	printf("\n");


}
int main()
{
	List L = CreatListHead(5);;
    PrintList(L,5);
	Insert(8, 3, L);
	PrintList(L, 6);
	Delete(3, L);
	PrintList(L, 5);
	DeleteList(L);
	system("pause");
    return 0;
}


你可能感兴趣的:(数据结构,单链表)