6-1 顺序表基本操作(10 分)

6-1 顺序表基本操作(10 分)

本题要求实现顺序表元素的增、删、查找以及顺序表输出共4个基本操作函数。L是一个顺序表,函数Status ListInsert_Sq(SqList &L, int pos, ElemType e)是在顺序表的pos位置插入一个元素e(pos应该从1开始),函数Status ListDelete_Sq(SqList &L, int pos, ElemType &e)是删除顺序表的pos位置的元素并用引用型参数e带回(pos应该从1开始),函数int ListLocate_Sq(SqList L, ElemType e)是查询元素e在顺序表的位次并返回(如有多个取第一个位置,返回的是位次,从1开始,不存在则返回0),函数void ListPrint_Sq(SqList L)是输出顺序表元素。实现时需考虑表满扩容的问题。

函数接口定义:
Status ListInsert_Sq(SqList &L, int pos, ElemType e);
Status ListDelete_Sq(SqList &L, int pos, ElemType &e);
int ListLocate_Sq(SqList L, ElemType e);
void ListPrint_Sq(SqList L);

其中 L 是顺序表。 pos 是位置; e 代表元素。当插入与删除操作中的pos参数非法时,函数返回ERROR,否则返回OK。

裁判测试程序样例:
//库函数头文件包含
#include<stdio.h>
#include<malloc.h>
#include<
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
顺序表是一种线性结构,可以通过连续的内存空间来存储元素。在C语言中,可以使用数实现顺序表。下面是顺序表基本操作: 1. 初始化顺序表: ```c #define MAX_SIZE 100 // 定义顺序表的最大长度 typedef struct { int data[MAX_SIZE]; // 存储数据的数 int length; // 当前顺序表的长度 } SeqList; void InitList(SeqList *list) { list->length = 0; // 初始化顺序表的长度为0 } ``` 2. 插入元素: ```c int Insert(SeqList *list, int pos, int element) { if (pos < 1 || pos > list->length + 1) { return 0; // 插入位置非法,返回失败 } if (list->length >= MAX_SIZE) { return -1; // 顺序表已满,返回失败 } for (int i = list->length; i >= pos; i--) { list->data[i] = list->data[i - 1]; // 向后移动元素 } list->data[pos - 1] = element; // 在插入位置插入新元素 list->length++; // 长度加1 return 1; // 插入成功 } ``` 3. 删除元素: ```c int Delete(SeqList *list, int pos) { if (pos < 1 || pos > list->length) { return 0; // 删除位置非法,返回失败 } for (int i = pos; i < list->length; i++) { list->data[i - 1] = list->data[i]; // 向前移动元素 } list->length--; // 长度减1 return 1; // 删除成功 } ``` 4. 查找元素: ```c int Search(SeqList *list, int element) { for (int i = 0; i < list->length; i++) { if (list->data[i] == element) { return i + 1; // 返回元素在顺序表中的位置 } } return 0; // 没有找到元素 } ``` 5. 获取指定位置的元素: ```c int GetElement(SeqList *list, int pos) { if (pos < 1 || pos > list->length) { return -1; // 位置非法,返回错误值 } return list->data[pos - 1]; // 返回指定位置的元素 } ``` 6. 修改指定位置的元素: ```c int Modify(SeqList *list, int pos, int element) { if (pos < 1 || pos > list->length) { return 0; // 位置非法,返回失败 } list->data[pos - 1] = element; // 修改指定位置的元素 return 1; // 修改成功 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值