1. Objectives of the experiment
1. Familiarize yourself with and master the methods and steps of compiling, debugging and executing in the Dev-C++ environment.
2. Familiar with the implementation of linear table sequential storage.
2. Experiment content
Implement operations such as inserting, deleting, and viewing the sequence table.
Operation menu requirements:
①Insert: Input the inserted position and data, and output the inserted data;
②Delete: Enter the position to be deleted, and output the deleted data;
③View: View the data in the current sequence table;
④Exit.
(The experiment content can use "int" as the data type of the sequence table data element.)
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--;
}
main.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;
}