1. Objetivos del experimento
1. Familiarizarse y dominar los métodos y pasos de compilación, depuración y ejecución en el entorno Dev-C++.
2. Familiarizarse con la implementación del almacenamiento secuencial de tablas lineales.
2. Experimente el contenido
Implemente operaciones como insertar, eliminar y ver la tabla de secuencias.
Requisitos del menú de operación:
①Insertar: Ingrese la posición y los datos insertados, y genere los datos insertados;
②Eliminar: Ingrese la posición que se eliminará y generará los datos eliminados;
③Ver: Ver los datos en la tabla de secuencia actual;
④Salir.
(El contenido del experimento puede usar "int" como el tipo de datos del elemento de datos de la tabla de secuencia).
SqLish.h
#include <malloc.h>
#include <stdio.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
}SqList; //顺序表类型
void CreateList(SqList * &L,ElemType a[],int n)
{
int i=0,k=0;
L=(SqList *)malloc(sizeof(SqList));
while (i<n) //i扫描a中元素
{
L->data[k]=a[i];
k++; i++; //k记录插入到L中的元素个数
}
L->length=k;
}
void InitList(SqList *&L) //引用型指针
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
void DestroyList(SqList *&L)//销毁顺序表
{
free(L);
}
bool ListEmpty(SqList *L)//判断顺序表是否为空
{
return(L->length==0);
}
int ListLength(SqList *L) //求顺序表长度
{
return(L->length);
}
void DispList(SqList *L)//显示顺序表
{
for(int i=0;i<L->length;i++)
printf("%4d",L->data[i]);
printf("\n");
}
bool GetElem(SqList *L,int i,ElemType &e)//获取顺序表L第i位置,用e返回
{
if(i<1 || i>L->length)
return false;
e=L->data[i-1];
return true;
}
bool ListInsert(SqList *L,int i,ElemType &e)// 在顺序表L第i位置,插入数据元素e
{
int j;
if(i<1 || i>L->length)
return false;
i--;
for(j=L->length;j>i;j--)
L->data[j]=L->data[j-1];
L->data[i]=e;
L->length++;
return true;
}
bool ListDelete(SqList *L,int i,ElemType &e)//删除 顺序表L第i位置,用e返回
{
int j;
if(i<1 || i>L->length)
return false;
i--;
e=L->data[i];
for(j=i;j<L->length-1;j++)
L->data[j]=L->data[j+1];
L->length--;
}
principal.h
#include <iostream>
#include <stdio.h>
#include "SqList.h"
int main(int argc, char** argv) {
SqList *L;
//*int类型
int a[10]={
1,2,2,4,5,6,7,8,9,10};
CreateList(L,a,10);//创建顺序表
printf("=====当前线性表为:\n");
DispList(L);//显示顺序表
printf("\n");
int n;
while(1)
{
printf("==============\n");
printf("1.插入数据\n");
printf("2.删除数据\n");
printf("3.查看数据\n");
printf("4.退出\n");
printf("==============请选择:");
scanf("%d",&n);
printf("\n\n\n");
switch (n)
{
case 1:
int i,j;
printf("=====请输入要插入的位置:");
scanf("%d",&i);
printf("=====请输入要插入的数据元素:");
scanf("%d",&j);
ListInsert(L,i,j);
printf("插入后的数据是:");
DispList(L);
printf("\n\n\n");
break;
case 2:
int a,b;
printf("=====请输入要删除的位置:");
scanf("%d",&a);
printf("=====删除的数据元素是:");
ListDelete(L,a,b);
printf("%d\n",b);
printf("删除后的数据是:");
DispList(L);
printf("\n\n\n");
break;
case 3:
printf("=====当前线性表为:\n");
DispList(L);
printf("\n\n\n");
break;
case 4:
return 0;
default:
printf("请输入正确的操作");
}
}
return 0;
}