顺序表的实现
1、实验目的与基本要求:
熟悉线性表顺序存储的实现方式。
2、实验内容:
实现顺序表的插入、删除、查看等操作。
操作菜单要求:
① 插入:输入插入的位置和数据,输出插入后的数据;
② 删除:输入要删除的位置,输出删除后的数据;
③ 查看:查看当前顺序表的数据;
④ 退出。
该实验内容以“int”作为顺序表数据元素的数据类型即可。
main.cpp文件
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "SqList.h"
int main()
{
ElemType e; //初始化元素e
SqList *L; //初始化线性表L
int array[10] = {0,1,2,3,4,5,6,7,8,9};
CreateSqList(L,10,array);
printf("显示当前的线性表元素:");
ShowSqList(L);
int n = 0;
int position;
while (n != 4)
{
printf("\n\n菜单\n==========\n1.插入数据\n2.删除数据\n3.查看数据\n4.退出\n==========\n\n");
printf("请选择1~4其中一个功能:");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\n请输入您要插入的位置:");
scanf("%d",&position);
printf("请输入您要插入的元素:");
scanf("%d",&e);
SqListInsert(L,position,e);
printf("插入后的数据是:\n");
ShowSqList(L);
continue;
case 2:
printf("\n请删除您要删除的位置:");
scanf("%d",&position);
SqListDelete(L,position);
printf("\n删除后的数据是:\n");
ShowSqList(L);
continue;
case 3:
printf("\n当前线性表为\n");
ShowSqList(L);
continue;
case 4:
printf("您已退出菜单");
break;
default:
printf("输入错误,请重新输入");
continue;
}
}
return 0;
}
SqList.h文件
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stdbool.h>
#include <malloc.h>
typedef int ElemType; //自定义整型类型ElemType
#define MaxSize 50
typedef struct //自定义结构体类型SqList
{
ElemType data[MaxSize]; //存放线性表中的元素
int length; //存放线性表的长度
}SqList; //顺序表的类型
void CreateSqList(SqList* &L,int n,ElemType array[])
{
L = (SqList *)malloc(sizeof(SqList)); //创建线性表需要开辟其存储空间
// for(int i = 0; i < n; i++)
// {
// L -> data[i] = array[i]; //将array数组的元素值赋值到线性表L中
// }
int i = 0;
int len = 0;
while(i < n)
{
L -> data[i] = array[i];
len++;
i++;
}
L->length = len;
}
void ShowSqList(SqList *L)
{
for(int i = 0; i < L->length; i++)
{
printf("%5d",L -> data[i]);
}
printf("\n");
}
bool SqListInsert(SqList* &L,int position,ElemType e)
{
if(position < 1 || position > L->length)
{
return 0; //参数 position 错误时返回 false
}
position -= 1; //将顺序表的逻辑序号转化为物理序号
int j = L->length;
while(j > position)
{
L -> data[j] = L -> data[j-1]; //将data[i]及后面的元素后移一个元素
j--;
}
// for(int i = L->length; i > position ;i--)
// {
// L->data[i] = L->data[i-1]; //将data[i]及后面的元素后移一个元素
// }
L->data[position] = e; //在position位置插入元素e
L->length += 1; //顺序表的长度加 1
return 1; //插入成功返回 true
}
bool SqListDelete(SqList* &L, int position)
{
if(position < 1 || position > L->length) //参数 position 错误时返回 false
{
return 0;
}
position -= 1; //将顺序表的逻辑序号转化为物理序号
int i = position;
int j = L->length-1;
while(i < j)
{
L->data[i] = L->data[i+1];
i++;
}
// for(int i = position; i < L->length-1; i++)
// {
// L->data[i] = L->data[i+1];
// }
L->length -= 1;
return 1;
}
运行结果