数据结构与算法分析——单链表

单链表
链表由一系列不必在内存中相邻的结构组成。每一个结构均含有表元素和指向包含该元素后继元的结构的指针,即Next指针。
代码实现如下
List.h

#ifndef _List_H

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

void InitList(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, List L, Position P);
void DeleteList(List L);
void PrintList(List L);

#endif /* _List_H */

struct Node
{
    ElementType Element;
    Position Next;
};

List.c

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

/* Return true is L is Empty */
int IsEmpty(List L)
{
    return L->Next == NULL;
}
/* 
* Return true is 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 */
Position Find(ElementType X, List L)
{
    Position P;

    P = L->Next;
    while(P!=NULL && P->Element!=X)
        P = P->Next;

    return P;
}

/*
* Delete first occurence 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;
        /* Bypass delete cell */
        P->Next = TmpCell->Next;
        free(TmpCell);
    }
}

/*
* If X is not found, then Next field of returned
* Position is NULL
* Assumes a header 
*/
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 P)
* Header implementation assumed
* Pasrameter L is unused in this implementation
*/
void Insert(ElementType X, List L, Position P)
{
    Position TmpCell;

    TmpCell = malloc(sizeof(struct Node));
    if(TmpCell == NULL){
        printf("Out of space!!!\n");
        exit(-1);
    }

    TmpCell->Element = X;
    TmpCell->Next = P->Next;
    P->Next = TmpCell;
}

/* Delete List */
void DeleteList(List L)
{
    Position P, Tmp;

    P = L->Next;
    L->Next = NULL;
    while(P!=NULL){
        Tmp = P->Next;
        free(P);
        P = Tmp;
    }
}

/* Print Elements of List */
void PrintList(List L)
{
    Position P;

    P = L->Next;
    while(P!=NULL)
    {
        printf("%3d", P->Element);
        P = P->Next;
    }
}

/* Initialize  List */
void InitList(List *L)
{
    (*L) = malloc(sizeof(struct Node));
    (*L) -> Next = NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值