1111111111

本文介绍了如何使用C语言实现顺序表的数据结构,包括ListMakeEmpty函数用于创建顺序表,PrintL函数用于打印表中元素,Find函数用于查找元素,Insert函数插入新元素,以及Delete函数删除指定位置的元素。
摘要由CSDN通过智能技术生成

List MakeEmpty()
{
    //malloc
    List L;
    L = (List)malloc(sizeof(struct LNode));
    if (L == NULL)
    {
        printf("顺序表创建失败\n");
        return L;
    }
 
    //initialize
    memset(L, 0, sizeof(struct LNode));
    L->Last = -1;
 
    //return
    return L;
}
 
void PrintL(List L)
{
    Position i;
 
    if (L == NULL)
        return ;
    if (L->Last == -1)
        printf("顺序表为空\n");
    else
        printf("顺序表的值为:");
    for (i = 0; i <= L->Last; i++)
    {
        printf("%d ", L->Data[i]);
    }
    puts("");
    return ;
}
 
Position Find(List L, ElementType X)
{
    for (Position i = 0; i <= L->Last; i++) 
    {
        if (L->Data[i] == X) {
            return i;
        }
    }
    return ERROR;
}
 
bool Insert(List L, ElementType X, int i)
{
    Position j;
 
    //full
    if (L->Last == MAXSIZE - 1 )
    {
        printf("顺序表满,无法插入\n");
        return false;
    }
 
    //check para 0<=i<=last+1
    if ((i < 0) || (i - 1 > (L->Last + 1)))
    {
        printf("插入位置不合法\n");
        return false;
    }
 
    //move
    for (j = L->Last; j >= i - 1; j--)
    {
        L->Data[j + 1] = L->Data[j];
    }
 
    //update value last
    L->Data[i - 1] = X;
    L->Last = L->Last + 1;
 
    return true;
}
bool Delete(List L, int i)
{
    Position j;
 
    if (L->Last == -1)
    {
        printf("顺序表为空\n");
        return false;
    }
 
    //pos [0, last]
    if (i < 0 || i - 1 > L->Last)
    {
        printf("位序%d不存在元素\n",i);
        return false;
    }
 
    //move [pos+1, last]
    for (j = i ; j <= L->Last; j++)
    {
        L->Data[j - 1] = L->Data[j];
    }
 
    //update
    L->Last--;
 
    return true;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值