1. 讲解:
2. C++代码实现:
#include <stdlib.h>
#include <iostream>
using namespace std;
#define InitSize 10
#define ElemType int
typedef struct {
ElemType* data; // 这里指针类型没问题,就当是a[10]里的a
int MaxSize;
int length;
}SeqList;
// 初始化
void InitList(SeqList& L) {
L.data = (ElemType*)malloc(InitSize * sizeof(ElemType)); // 动态分配内存大小
L.length = 0;
L.MaxSize = InitSize;
}
// 动态增加顺序表长度
void IncreaseSize(SeqList& L, int len) {
ElemType* p = L.data;
L.data = (ElemType*)malloc(L.MaxSize + len * sizeof(ElemType)); // 动态分配内存大小
for (int i = 0; i < L.length; i++) {
L.data[i] = p[i];
}
L.MaxSize += len;
free(p);
}
// 按位序插入元素
bool ListInsert(SeqList& L, int i, ElemType e) {
if (i < 1 || i > L.length + 1) return false; // 非法位置插入
if (L.length >= L.MaxSize) return false; // 满了
for (int j = L.length; j >= i; j--) L.data[j] = L.data[j - 1]; // 腾出空间
L.data[i - 1] = e;
L.length++;
return true;
}
// 按位序删除元素
bool ListDelete(SeqList& L, int i, ElemType& e) {
if (i < 1 || i > L.length) return false; // 非法位置读取
e = L.data[i - 1];
for (int j = i; j <= L.length - 1; j++) L.data[j - 1] = L.data[j];// 向前覆盖
L.length--;
return true;
}
// 按位查找
ElemType GetElem(SeqList L, int i) {
return L.data[i - 1];
}
// 按值查找
int LocateElem(SeqList L, ElemType e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) return i + 1;
}
return 0; // 没找到则返回0
}
int main() {
SeqList myList;
InitList(myList); // 初始化顺序表
// 向顺序表中插入一些元素
for (int i = 1; i <= 5; i++) {
ListInsert(myList, i, i);
}
// 输出顺序表中的元素
cout << "顺序表中的元素为:";
for (int i = 1; i <= myList.length; i++) {
cout << GetElem(myList, i) << " ";
}
cout << endl;
// 在第3个位置插入元素10
ListInsert(myList, 3, 10);
// 输出插入后的顺序表中的元素
cout << "插入元素后的顺序表中的元素为:";
for (int i = 1; i <= myList.length; i++) {
cout << GetElem(myList, i) << " ";
}
cout << endl;
// 删除第4个位置的元素
ElemType deletedElem;
ListDelete(myList, 4, deletedElem);
// 输出删除后的顺序表中的元素
cout << "删除元素后的顺序表中的元素为:";
for (int i = 1; i <= myList.length; i++) {
cout << GetElem(myList, i) << " ";
}
cout << endl;
// 查找元素7在顺序表中的位置
int position = LocateElem(myList, 7);
if (position != 0) {
cout << "元素7在顺序表中的位置为:" << position << endl;
}
else {
cout << "元素7不在顺序表中" << endl;
}
// 清空顺序表
free(myList.data);
return 0;
}
小结:
关注我给大家分享更多有趣的知识,以下是个人公众号,提供 ||代码兼职|| ||代码问题求解||
添加我的公众号即可: