欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

考研22计408科目指南:数据结构里的顺序表详解

最编程 2024-07-30 09:18:52
...
// 顺序表 #include <iostream> #define MAXSIZE 1001 using namespace std; typedef struct { //定义学生结构体,包含学号和姓名 char ID[20]; char name[50]; } Student; typedef struct { //定义线性表,和长度属性 Student *elem; int length; } StuList; bool ListInit(StuList &L) { //初始化线性表 L.elem = new Student[MAXSIZE]; //给数组分配空间长度 if (!L.elem) { //如果没分配成功,就返回失败 return false; } L.length = 0; //初始化线性表后长度为0 return true; } //插入的时候需要注意把这一位后面的,每个都后移一位,然后把数据放到空出来的那位 bool ListInsert(StuList &L, int i, Student stu) { //把Student类型插入到序列为i的位置 if (i < 0 || i > L.length + 1) { //判断插入位置是否正确 return false; } if (L.length == MAXSIZE) { //如果插入位置到达最大值,无法插入 return false; } for (int j = L.length - 1; j >= i - 1; j--) { //把i以后元素都向后移动一位, L.elem[j + 1] = L.elem[j]; } L.elem[i - 1] = stu; //把将要插入的放到指定位置 ++L.length; //线性表长度+1 return true; } //也是和插入的时候一样,把i后面的都向前移动一位 bool ListDelete(StuList &L, int i) { //删除序列为i的元素 if (i < 1 || i > L.length) { return false; } for (int j = i; j < L.length; j++) { //把序列i以后的元素全部前移一位,盖住了序列为i的那位 L.elem[j - 1] = L.elem[j]; } --L.length; //线性表长度-1 return true; } bool ListGetStu(StuList &L, int i, Student &s) { //返回序列为i的元素 if (i < 1 || i > L.length) { return false; } s = L.elem[i - 1]; return true; } int ListGetIndex(StuList &L, Student s) { //找到与s相等的元素的下标 for (int i = 0; i < L.length; i++) { if (L.elem[i].ID == s.ID && L.elem[i].name == s.name) { return i + 1; } } return 0; } void ListMerge(StuList &A, StuList B) { //把B表中A表没有的元素插入到A表后面 int a = A.length, b = B.length; for (int i = 0; i < B.length; i++) { if (!ListGetIndex(A, B.elem[i])) { //A表中是否存在B.elem[i] ListInsert(A, ++a,B.elem[i]); } } A.length = a; //a代表新线性表的大小,初始为A线性表大小,后面每次插入到A线性表一个值,a++ } void ListaddAll (StuList &A, StuList B) { //把B线性表插入到A线性表后面 int a = A.length, b = B.length; for (int i = 0; i < B.length; i++) { ListInsert(A, ++a,B.elem[i]); } A.length = a; } int main() { StuList demo; ListInit(demo); Student student = {"123", "张三"}; Student student2 = {"456", "李三"}; ListInsert(demo, 1, student); ListInsert(demo, 2, student2); ListGetStu(demo, 1, student2); cout << student2.ID << student2.name << "\n"; cout << ListGetIndex(demo, student) << "\n"; ListMerge(demo, demo); ListaddAll(demo, demo); cout << demo.length; return 0; }