数据结构_顺序列表_插入算法

别等时光非礼了梦想. 提交于 2020-01-22 19:34:28

数据结构之顺序列表之插入算法

关于这个,只怪自己寒假里无法完全集中精力,看老九军的这一节网课重复看了三天,才弄清了些东西。

对于刚开始接触编程的初学者,这里要引入一个索引下标以及位置的概念

但是在这里不多介绍,可自行百度。

顺序表的插入算法实现的步骤

  1. 判断插入的索引index是否合法。
    比如index是否小于0,是否超出了容器规定的最大范围。
  2. 判断容器内的元素是否已满。
  3. 判断插入的索引index是否在容器长度之内。
  4. 从下标为index的元素开始,每个元素往右移动一个位置。
  5. 表长度length+1。(容易忘记的地方)

C++代码

#pragma once
constexpr auto MAX_SIZE = 255;//定义容器的最大容量;
#include <iostream>
using namespace std;
typedef struct {
	int id;
	char* name;
}ElementType;//数据元素
typedef struct {
	ElementType datas[MAX_SIZE];
	int length;
}SeqList;//定义顺序列表
void InsertElement(SeqList* seqlist, int index, ElementType element)//插入算法
{
	//1、验证插入后的元素空间是否超过MAX_SIZE
	//2、index的值是否合法[0,MAX_ SIZE-1]
	//3、插入的index应该在length之内
	//4、从第length-1个下标开始,前面一个元素赋值给后面一个元素
	if (seqlist->length + 1 >= MAX_SIZE) {//判断容器元素是否已满
		cout << "数组已满,插入元素失败!\n";
		return;
	}
	if (index<0 || index>MAX_SIZE - 1) {//判断插入位置是否合法
		cout << "只能在允许得范围内插入元素!\n";
		return;
	}
	if (index > seqlist->length) {//判断插入的位置是否在length之内
		cout << "插入下标超过了最大长度,插入失败!\n";
		return;
	}
	for (int i = seqlist->length - 1; i >= index; i--) {
		seqlist->datas[i + 1] = seqlist->datas[i];
	}
	seqlist->datas[index] = element;
	seqlist->length = seqlist->length + 1;
}
void InitList(SeqList* seqlist, ElementType* elemArray, int length)//初始化
{
	seqlist->length = 0;
	
	if (seqlist->length > MAX_SIZE) {
		cout << "超出了数组容量的最大范围\n";
		return;
	}
	for (int i = 0; i < length; i++) {
		InsertElement(seqlist, i, elemArray[i]);
	}
}
void PrintList(SeqList* seqlist)//打印结果
{
	for (int i = 0; i < seqlist->length ; i++) {
		cout << seqlist->datas[i].id << "\t" << seqlist->datas[i].name << endl;
	}
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!