线性表的插入和创建(完整程序)

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

#define OK 1
#define ERROR -1
#define MAX_SIZE 100

typedef int Status;
typedef int ElemType;

typedef struct sqlist
{
    ElemType Elem_array[MAX_SIZE];
    int length;
}Sqlist;


//插入运算

Status InsertElem(Sqlist *L,int i,ElemType e)
{
    int j;
    if(i<0||i>L->length + 1)
        return ERROR;
    if(L->length>MAX_SIZE)
    {
        printf("线性表溢出!\n");
    }

    for(j = L->length-1;j>=i-1;j--)
    {
        L->Elem_array[j+1] = L->Elem_array[j];
    }
    L->Elem_array[i-1]  = e;
    L->length++;
    return OK;
}

void PrintList(Sqlist *L)
{

    int i;
    for(i = 0;i<L->length;i++)
    {
        printf("%d\n",L->Elem_array[i]);

    }

}

void main()
{
    Sqlist l;
    l.length = 0;
   //int l->Elem_array[MAX_SIZE];
    InsertElem(&l,1,2);
    InsertElem(&l,2,2);
    InsertElem(&l,3,2);

    PrintList(&l);
}

这里写图片描述
如果想直接创建一个线性表,程序如下:

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

#define OK 1
#define ERROR -1
#define MAX_SIZE 100

typedef int Status;
typedef int ElemType;

typedef struct sqlist
{
    ElemType Elem_array[MAX_SIZE];
    int length;
}Sqlist;


//插入运算

Status InsertElem(Sqlist *L,int i,ElemType e)
{
    int j;
    if(i<0||i>L->length + 1)
        return ERROR;
    if(L->length>MAX_SIZE)
    {
        printf("线性表溢出!\n");
    }

    for(j = L->length-1;j>=i-1;j--)
    {
        L->Elem_array[j+1] = L->Elem_array[j];
    }
    L->Elem_array[i-1]  = e;
    L->length++;
    return OK;
}

void PrintList(Sqlist *L)
{

    int i;

    for(i = 0;i<L->length;i++)
    {

        printf("%d\n",L->Elem_array[i]);

    }

}


Status CreatList(Sqlist *L)
{

    int len;
    int i;
    //ElemType q;
    printf("请输入想要创建表的长度:");
        scanf("%d",&len);
    if(len<0||len>MAX_SIZE)
        return ERROR;
    L->length = len;
    for(i = 0;i<len;i++)
    {
        scanf("%d",&L->Elem_array[i]);

    }



}

void main()
{
    Sqlist l;
    l.length = 0;
   //int l->Elem_array[MAX_SIZE];
    //InsertElem(&l,1,2);
    //InsertElem(&l,2,2);
    //InsertElem(&l,3,2);

    CreatList(&l);

printf("线性表的值如下:\n");
    PrintList(&l);

    InsertElem(&l,3,2);
printf("插入数值后的线性表如下:\n");
    PrintList(&l);
}

这里写图片描述

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值