顺序表的实现

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);
}

其运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言乐卿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值