线性表分为顺序表与链表
其中顺序表用存储位置的相邻来体现数据元素之间的逻辑关系,可以以静态分配或者动态分配方式实现
其基本操作有插入、删除、按位查找、按值查找等
/*
顺序表:用顺序存储的方式实现的线性表
逻辑结构:线性表
物理结构:顺序表-静态分配
*/
#include<cstdio>
#include<iostream>
using namespace std;
#define MaxSize 10 //定义线性表最大长度
#define ElemType int
typedef struct {
ElemType data[MaxSize]; //顺序表的元素
int length; //顺序表当前长度
}SqList; //顺序表类型定义
//初始化顺序表
void InitList(SqList& L) {
for (int i = 0; i < MaxSize; i++)
L.data[i] = 0;
L.length = 0; //顺序表初始长度为0
}
//顺序表建立(C语言1)
void InitListC1(SqList& L) {
int count=0;
cout << "请为顺序表指定初始情况,元素之间空格间隔,长度上限为10,回车结束:\n";
do {
scanf_s("%d",&L.data[count++]);
L.length++;
} while (getchar() != '\n' && L.length<MaxSize);
}
//顺序表建立(C++1)
void InitListCpp1(SqList& L) {
int count = 0;
ElemType e;
cout << "请为顺序表指定初始情况,元素之间回车间隔,999结束:\n";
cin >> e;
while (e!=999) {
L.data[L.length] = e;
L.length++;
cin >> e;
}
}
//打印顺序表
void PrintList(SqList L) {
for (int i = 0; i < L.length; i++) {
cout << L.data[i];
cout << " ";
}
cout << "\n";
}
//插入
bool ListInsert(SqList& L, int i, ElemType e) { //i是位序(1~n)
if (i<1 || i>L.length + 1) return false;
if (L.length >= MaxSize)return false;
for (int j = L.length; j >= i; j--) //j是数组下标
L.data[j] = L.data[j - 1];
L.data[i - 1] = e;
L.length++;
return true;
}
//删除
bool ListDelete(SqList& L, int i, ElemType &e) {
if (i<1 || i>L.length + 1) return false;
e = L.data[i - 1];
for (int j = i; j < L.length; j++)
L.data[j - 1] = L.data[j];
L.length--;
return true;
}
//按位查找
ElemType GetElem(SqList L, int i) {
return L.data[i - 1];
}
//按值查找
int LocateElem(SqList L, ElemType e) {
for (int i = 0; i < L.length; i++)
if (L.data[i] == e)
return i + 1;
return 0;
}
//更完备按值查找
void LocateElem2(SqList L, ElemType e,int ee[]) {
int ii = 1;
for (int i = 0; i < L.length; i++)
if (L.data[i] == e)
ee[ii++] = i + 1;
}
//判断操作
void Judge(string s,bool b) {
if (b) {
cout << s;
cout << "操作成功\n";
}
else {
cout << s;
cout << "操作失败\n";
}
}
int main() {
SqList L; //声明一个顺序表
InitList(L); //初始化顺序表
InitListC1(L); //顺序表初始情况指定
cout << "输出初始化后的静态分配顺序表:\n";
PrintList(L);
Judge("Insert1", ListInsert(L, 3, 6));
Judge("Insert2", ListInsert(L, 4, 9));
cout << "输出插入后的静态分配顺序表:\n";
PrintList(L);
ElemType e1;
Judge("Delete1", ListDelete(L, 5, e1));
cout << "输出删除操作后的静态分配顺序表:\n";
PrintList(L);
cout << "被删除的元素为:\n";
cout << e1;
cout << "\n";
return 0;
}