要求实现递增顺序表的插入操作。
L是一个递增的有序顺序表
简单注释都在代码里,一目了然。
测试了输出的操作,自己试了多次,符合预期结果
主要步骤:
bool ListInsert(SeqList& L, int i, int e) //插入操作,在第 i 位插入
{
if (i<1|| i>L.Length+1)
return false;
if (L.Length >= MaxSize)
return false;
for (int j = L.Length; j >= i;j--)
L.data[j] = L.data[j - 1];
L.data[i] = e;
L.Length++;
}
完整测试代码:
#include<iostream>
using namespace std;
#define MaxSize 10 //默认最大长度
typedef struct //线性表的自定义结构体
{
int data[MaxSize];
int Length; //当前表长
}SeqList;
void InitList(SeqList& L) //线性表的初始化
{
int Length = 6;
for (int i = 0; i <Length; i++)
{
L.data[i] = i;
}
}
bool ListInsert(SeqList& L, int i, int e) //插入操作,在第 i 位插入
{
if (i<1|| i>L.Length+1)
return false;
if (L.Length >= MaxSize)
return false;
for (int j = L.Length; j >= i;j--)
L.data[j] = L.data[j - 1];
L.data[i] = e;
L.Length++;
for (int i = 0; i <L.Length; i++)
{
cout << "第"<<i<<"个数是"<<L.data[i] << endl;
}
cout << "Length=" << L.Length << endl;
return true;
}
void test01() //测试
{
SeqList L;
InitList(L);
L.Length = 6;
for (int i = 0; i <L.Length; i++) //遍历输出
{
cout << "第" << i << "个数是" << L.data[i] << endl;
}
cout << "当前长度Length=" << L.Length << endl<<endl;
cout << "在第2 个元素插入 5" << endl;
cout << "结果是" << endl;
ListInsert(L,2,5);
}
int main() //主函数,调用
{
test01();
system("pause");
return 0;
}