Demo entry 6729097

c语言

   

Submitted by xu on Apr 01, 2018 at 12:32
Language: C. Code size: 2.7 kB.

#include<stdio.h>
#include<stdlib.h>
#define LISTINITSIZE 100
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;

typedef struct sqlist
{
    ElemType *elem;
    int length;
    int listsize;a
}sqlist;
//初始化顺序表
Status initlist_sq(sqlist *L)
{
    L->elem=(ElemType*)malloc(LISTINITSIZE*sizeof(sqlist));
    L->length=0;
    L->listsize=0;
    return OK;
}
//创建顺序表
Status createlist_sq(sqlist *L)
{
    int n;
    system("cls");
    printf("*******创建顺序表*********\n");
    printf("请输入顺序表的长度:");
    scanf("%d",&n);
    L->length=n;
    for(int i=0;i<n;i++)
    {
        printf("\n请输入第%d个整数: ",i+1);
        scanf("%d",&L->elem[i]);
    }
    printf("\n创建成功!");
    getchar();
    return OK;
}
//遍历输出顺序表
void traverlist_sq(sqlist *L)
{
    system("cls");
    printf("顺序表的长度为:%d\n",L->length);
    printf("元素为:\n");
    for(int i=0;i<L->length;i++)
        printf("%5d",L->elem[i]);
    printf("\n");
    printf("按任意键继续!");
    getchar();
}
//顺序表的插入
Status listInsert_sq(sqlist *L)
{
    int location,element;
    system("cls");
    printf("请输入插入的位置:");
    scanf("%d",&location);
    if(location<1||(location>L->length+1))    return ERROR;
    if(L->length==LISTINITSIZE)        return ERROR;
    printf("请输入要插入的元素:");
    scanf("%d",&element);
    for(int j=L->length-1;j>=location;j--)
        L->elem[j+1]=L->elem[j];
    L->elem[location-1]=element;
    ++L->length;
    printf("按任意键继续!");
    getchar();

    return OK;

}
//删除顺序表中的元素
Status listDelete_sq(sqlist *L)
{
    int location;
    system("cls");
    printf("请输入删除的位置:");
    scanf("%d",&location);
    if(location<1||(location>L->length+1))   return ERROR;
    for(int i=location;i<=L->length-1;i++)
        L->elem[i-1]=L->elem[i];
    --L->length;
    printf("按任意键继续!");
    getchar();

    return OK;
}
//显示菜单函数
void menu()
{
    printf("************************************************************************\n");
    printf("            1.创建顺序表             2.输出顺序表\n\n");
    printf("            3.增加表元素             4.删除表元素\n\n");
    printf("************************************************************************");
}
int main(void)
{
    int choose;
    sqlist listL;
    sqlist *L=&listL;
    if(!initlist_sq(L))
        printf("初始化顺序表失败!");
    while(1)
    {
        menu();
        printf("\n请输入操作序号:");
        scanf("%d",&choose);
        switch(choose)
        {
        case 1: createlist_sq(L);   break;
        case 2: traverlist_sq(L);   break;
        case 3: listInsert_sq(L);   break;
        case 4: listDelete_sq(L);   break;
        }
        getchar();
        system("cls");
    }

    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).