单链表

单链表练习记录
 #include <stdio.h>
 #include<stdlib.h>
//相关操作:创建,清空,查空,插入,查询,排序

typedef int ElemType;

typedef struct Node{
    ElemType data;
    struct Node *next;
}Node, *LinkedList;

LinkedList InitList(void)   //主要要分配空间,
{
    Node *L; // 头指针
    L = (Node *)malloc(sizeof(Node));
    if(L == NULL)
    {
        printf("apply for memory failed!\n");
    }
    L->data = 0;
    L->next = NULL;
    return L;
}

bool ListEmpty(LinkedList L)
{
    if (L->next == NULL)
        return true;
    else
        return false;
}

void ClearList(LinkedList L)
{
    LinkedList head = L;
    while (L->next != NULL)
    {
        LinkedList L_next = L;
        L = L_next->next;
        free(L_next);
    }
    free(L);
    head->data = 0;
    head->next = NULL;
}

void  ListInsert(LinkedList L, ElemType element)
{
    L->data += 1;
    while (L->next != NULL)
        L = L->next;
    L->next = (Node *)malloc(sizeof(Node));
    L = L->next;
    L->data = element;
    L->next = NULL;
}


void GetElem(LinkedList L, int i, ElemType& e)
{
    if (L->data < i)
    {
        printf("out of length\n");
    }
    else
    {
        while (i)
        {
            L = L->next;
            i--;
        }
        e = L->data;
    }
}

int LocateElem(LinkedList L, ElemType e)
{
    int i = 0;
    while (L->next != NULL)
    {
        L = L->next;
        i++;
        if (L->data == e)
        {
            return i;
        }
    }
}

void ListDelete(LinkedList L, ElemType e)
{
    while (L->next != NULL)
    {
        LinkedList L_n = L->next;
        if (L_n->data == e)
        {
            L->next = L_n->next;
            free(L_n);
            printf("Delete the element!\n");
            return;
        }
        else
        {
            L = L_n;
        }
    }
    printf("The element is not in the list!\n");
}


int main(int argc, char **argv)
{
    LinkedList L1;
    ElemType e1;
    int location;
    int result;
    L1 = InitList();
    result = ListEmpty(L1);
    ListInsert(L1, 1);
    ListInsert(L1, 3);
    ListInsert(L1, 4);
    ListInsert(L1, 5);

    GetElem(L1, 2, e1);
    location = LocateElem(L1, 3);
    ListDelete(L1,3);
    ClearList(L1);


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值