美文网首页
线性表之链表存储代码

线性表之链表存储代码

作者: 飒风灬 | 来源:发表于2018-07-21 13:56 被阅读0次

    include <stdio.h>

    define ElementType int

    typedef struct Node{
    ElementType Date;
    struct Node *Next;
    }List;

    List l, *Ptrl;

    //求表长
    int length(List *Ptrl)
    {
    List *p = Ptrl;
    int j = 0;
    while(p)
    {
    p = p -> Next;
    j++;
    }
    return j;
    }
    //只能序号查找
    List *FindKth(int k, List *Ptrl)
    {
    List *p = Ptrl;
    int i = 1;
    while(p != NULL && i< k)
    {
    p = p -> Next;
    i++;
    }
    if(i == k)
    return p;
    else
    return NULL;
    }

    //按值查找

    List Find(ElementType x, List *Ptrl)
    {
    List *p = Ptrl;
    while(p != NULL && p -> Date != x)
    p = p -> Next;
    return p;
    }

    //链表插入
    List *Insert(ElementType x, int i, List *Ptrl)
    {
    List *p, *s;
    if(i == 1)
    {
    s = (List *)malloc(sizeof(List));
    s -> Date = x;
    s -> Next = Ptrl;
    return s;
    }
    p = FindKth(i-1, Ptrl);
    if(p == NULL)
    {
    return NULL;
    }
    else
    {
    s = (List *)malloc(sizeof(List));
    s -> Date = x;
    s -> Next = p -> Next;
    p -> Next = s;
    return Ptrl;
    }
    }

    //链表删除
    List *Delete(int i, List *Ptrl)
    {
    List *p, *s;
    if(i == 1)
    {
    s = Ptrl;
    if(Ptrl != NULL)
    Ptrl = Ptrl -> Next;
    else
    return NULL
    free(s);
    return Ptrl;
    }
    p = FindKth(i-1, Ptrl);
    if(p == NULL)
    {
    //第n-1个几点不存在
    return NULL;
    }
    else if(p -> Next == NULL)
    {
    //第n个几点不存在
    return NULL;
    }
    else
    {
    s = p -> Next;
    p -> Next = s -> Next;
    free(s)
    return Ptrl;
    }
    }

    相关文章

      网友评论

          本文标题:线性表之链表存储代码

          本文链接:https://www.haomeiwen.com/subject/wmjhmftx.html