顺序表的的基本操作


#include<stdio.h>
#include<stdlib.h>
#define maxsize 1024
typedef char elemtype;
 
typedef struct
{
    elemtype list[maxsize];
    int length;
}sequenlist;
 
void creatlist(sequenlist *L)
{
    int n,i;
    char tmp;
    printf("请输入数据的个数:\n");
    scanf("%d",&n);
    printf("请按顺序输入各个值:\n");
    for(i=0;i<n;i++)
    {
        printf("list[%d]=",i);
        fflush(stdin); 
        scanf("%c",&tmp);
        L->list[i]=tmp;
    }
    L->length=n;
    printf("\n");
}
int insert(sequenlist *L,elemtype x,int i)  
{
    int j;
    if(L->length==maxsize)
    {
        printf("overflow\n");
        return 0;
    }
    else if((i<1)||(i>L->length+1))  
    {
        printf("error,please input the right'i'\n");
        return 0;
    }
    else
    {
        for(j=L->length-1;j>=i-1;j--)
            L->list[j+1]=L->list[j];
        L->list[i-1]=x;    
        L->length=L->length+1;    
        return 1;
    }
    
}
int dellist(sequenlist *L,int i)  
{
    if((i<1)||(i>L->length))
    {
        printf("error,please input the right 'i'\n");
        return 0;
    }
    else
    {
        for(;i<L->length;i++)
            L->list[i-1]=L->list[i];
        L->length=L->length-1;
        return 1;
    }
}
 
void printout(sequenlist *L)
{
    int i;
    for(i=0;i<L->length;i++)
    {
        printf("list[%d]=",i);
        printf("%c\n",L->list[i]);
    }
}
int main()
{
    sequenlist *L;
    char cmd,x;
    int i;
    L=(sequenlist *)malloc(sizeof(sequenlist));
    creatlist(L);
    printout(L);
    do
    {
        printf("i,I...插入\n");
        printf("d,D...删除\n");
        printf("q,Q...退出\n");
        do
        {
            fflush(stdin);
            scanf("%c",&cmd);
        }
        while((cmd!='d')&&(cmd!='D')&&(cmd!='q')&&(cmd!='Q')&&(cmd!='i')&&(cmd!='I'));
        switch(cmd)
        {
        case'i':
        case'I':
            printf("请输入要插入的数据:");
            fflush(stdin);
            scanf("%c",&x);
            printf("请输入要插入的位置:");
            scanf("%d",&i);
            insert(L,x,i);
            printout(L);
            break;
        case'd':
        case'D':
            printf("请输入要删除的数据的位置:");
            fflush(stdin);
            scanf("%d",&i);
            dellist(L,i);
            printout(L);
            break;
        }
    }
    while((cmd!='q')&&(cmd!='Q'));
}
 
 a2360cce6c534b8b84311151071b17dd.jpg

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值