顺序表的简单实现

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

#define MAXSIZE 100
typedef struct List
{
    int data[MAXSIZE];
    int length;
} List;

//初始化
void InitList(List *L)
{
    L->length = 0;
    return ;
}
//清空
void ClearList(List *L)
{
    L->length = 0;
    return ;
}

//插入
//插入时下标是从0~length-1,而不是1~length
void InsertList(List *L,int p,int e)
{
    if(L->length-1 == MAXSIZE)
    {
        printf("The List is full.\n");
        return ;
    }
    if(p<0 || p>L->length)
    {
        printf("Please input a new position.\n");
        return ;
    }

    //如果插入位置p刚好在原List最后一个元素的后面
    //则不需要进行for循环
    if(p<=L->length-1)
        for(int i = L->length-1; i>=p; i--)
        {
            L->data[i+1] = L->data[i];
        }

    L->data[p] = e;
    L->length++;

    return;
}

//删除
void DeleteList(List *L,int p,int *e)
{
    if(p<0 || p>L->length-1)
    {
        printf("Please input a new position.\n");
        return ;
    }

    *e = L->data[p];
    for(int i=p; i<L->length-1; i++)
        L->data[i] = L->data[i+1];

    L->length--;

}
//打印
void PrintList(List L)
{
    if(L.length == 0)
    {
        printf("The List is empty.\n");
        return ;
    }
    for(int i=0; i<L.length; i++)
        printf("%d ",L.data[i]);

    printf("\n\n");
}
int main()
{
    List L;
    InitList(&L);
    printf("L.length == %d\n",L.length);

    InsertList(&L,0,12);
    InsertList(&L,0,23);
    InsertList(&L,1,78);
    InsertList(&L,3,99);
    printf("After Insert.\nPrint the List: ");
    printf("L.length == %d\n",L.length);
    PrintList(L);

    int e = 0;
    DeleteList(&L,0,&e);
    printf("e = %d\n",e);
    DeleteList(&L,2,&e);
    printf("e = %d\n",e);
    printf("After Delete.\nPrint the List: ");
    printf("L.length == %d\n",L.length);
    PrintList(L);

    ClearList(&L);
    printf("After Clear.\nPrint the List: ");
    printf("L.length == %d\n",L.length);
    PrintList(L);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值