1.顺序表的存储结构
typedef struct{
Elemtype *elem;//定义一个指向空间基地址的指针
int lengrh;//定义当前表长
}sqList;
2.头文件与宏定义
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int status;
typedef int Elemtype;
其中使用c++输入输出头文件#include<iostream> using namespace std;
typedef 关键字来定义自己习惯的数据类型名称,来替代系统默认的基本类型名称、数组类型名称、指针类型名称与用户自定义的结构型名称、共用型名称、枚举型名称等
具体实现代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int status;
typedef int Elemtype;
typedef struct
{
Elemtype* elem;
int length;
}sqList;
sqList L;
status InitList(sqList& L)
{//初始化顺序表
L.elem = new Elemtype[MAXSIZE];//分配Elemtype类型的数组空间并使指针指向该空间的基地址
if (!L.elem) return ERROR;//若指针指向为空,则空间分配失败,退出
L.length = 0;//定义当前表长为零
return OK;
}
status CreatList(sqList& L,int n)
{//创建顺序表
printf("请输入所要填入表中的数据个数:\n");
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
{
cout << "请输入要如表的数据:\n";
cin >> L.elem[i];
L.length++;
}
return OK;
}
void TraverseList(sqList L)
{//遍历顺序表
for (int i = 0; i < L.length; i++)
{
cout <<L.elem[i]<<" ";
}
}
status GetListelem(sqList L, int n, Elemtype &e)
{//取值
if (n<1 || n>L.length) return ERROR;//n值不合法则退出
e = L.elem[n - 1];//数组下标从零开始因此顺序表序列减一为其在数组空间中的下标
return OK;
}
status LocatListelem(sqList L, int x, Elemtype e)
{//查找元素在顺序表中的位置
for (int i = 0; i < L.length; i++)
{
if (e == (L.elem[i]))
{
x = i + 1;
break;
}
}
return x;
}
status ListInsert(sqList& L,int n, Elemtype e)
{//插入
if (n<1 || n>L.length) return ERROR;
if (L.length == MAXSIZE) return ERROR;
for (int i = L.length-1; i >= n - 1; i--)
{
L.elem[i+1] = L.elem[i ];//将插入后的元素向后移一位,即将前一位的值赋给后一位;
}
L.elem[n - 1] = e;
L.length++;
return OK;
}
status ListDelete(sqList& L, int n)
{
if (n<1 || n>L.length) return ERROR;
for (int i = n; i < L.length - 1; i++)
{
L.elem[i-1] = L.elem[i ];//将删除后的数赋值前一位
}
L.length--;
return OK;
}
int main()
{
int n = 0;
int x = 0;
Elemtype e = 0;
sqList L;
InitList(L);
CreatList(L, n);
printf("此时的顺序表为:\n");
TraverseList(L);
printf("\n");
printf("请输入要查询元素的序列:\n");
scanf_s("%d", &n);
GetListelem(L, n, e);
cout << e;
printf("\n");
printf("请输入要查找的元素:\n");
scanf_s("%d", &e);
cout<<LocatListelem(L,x, e);
printf("\n");
printf("请输入要插入的位置和元素(其间用空格隔开)\n");
scanf_s("%d %d", &n, &e);
ListInsert(L, n, e);
TraverseList(L);
printf("\n");
printf("请输入要删除的序列:\n");
scanf_s("%d",&n);
ListDelete(L, n);
TraverseList(L);
}
其运行结果如下: