1.设计整数顺序表的基本运算程序,并用相关数据进行测试。具体步骤如下:
(1)定义顺序表类型SqList;
(2)编写子函数InitList(SqList &L),实现顺序表的初始化;
(3)编写子函数CreateList(SqList &L),实现顺序表的创建,从键盘上依次输入整型数据元素,创建顺序表;
(4)编写子函数InsElem(SqList &L, int x, int i),实现顺序表中的插入运算;
(5)编写子函数DelElem(SqList &L, int i),实现顺序表中的删除运算;
(6)编写子函数DispList(SqList L),实现顺序表的打印输出;
(7)编写主函数,在主函数中调用上述子函数,
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef int ElemType;
typedef struct
{
ElemType* elem;
int length;
}Sqlist;
void InitList(Sqlist& L)
{
L.elem = new ElemType[MAXSIZE];
L.length = 0;
}
void CreatList(Sqlist &L)
{
int i, n;
cout << "输入元素个数:" << endl;
cin >> n;
cout << "依次输入元素:" << endl;
for (i = 0; i < n; i++)
{
cin >> L.elem[i];
}
L.length = n;
}
int InsElem(Sqlist& L,int i,int e)
{
int j;
if (i<1 ||( i>L.length + 1))
return 0;
for (j = L.length-1; j>=i-1; j--)
L.elem[j+1] = L.elem[j];
L.elem[i - 1] = e;
L.length++;
return 1;
}
int DelElem(Sqlist& L,int i)
{
if ((i < 1) || (i > L.length))
return 0;
for (int j = i; j <= L.length; j++)
L.elem[j - 1] = L.elem[j];
L.length--;
return 1;
}
void DispList(Sqlist L)
{
int i;
for (i = 0; i < L.length; i++)
{
cout << L.elem[i];
}
}
int main()
{
Sqlist L;
InitList(L);
CreatList(L);
InsElem(L, 2, 4);
DelElem(L, 3);
DispList(L);
return 0;
}