22计算机408考研—数据结构—顺序表

204 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情

2022计算机考研408—数据结构—线性表、栈、队列、数组 手把手教学考研大纲范围内的线性表、栈、队列、数组 22考研大纲数据结构要求的是C/C++,笔者以前使用的都是Java,对于C++还很欠缺, 如有什么建议或者不足欢迎大佬评论区或者私信指出

Talk is cheap. Show me the code. 理论到处都有,代码加例题自己练习才能真的学会

顺序表

官方含义:一段地址连续的存储单元依次存储线性表的数据元素。
其实就相当于数组,`把顺序表当数组看`最简单了
 // 顺序表

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

在这里插入图片描述

顺序表和链表的区别

顺序表链表
插入删除效率低插入删除效率高
存取元素效率高存取元素效率高
顺序表在空间中是一块连续的地址链表在空间中地址不连续