题目:线性表的基本操作(要求必须采用顺序存储结构)
[问题描述]
实现线性表的建立、求长度,取元素、修改元素、插入、删除等基本操作。要求采用顺序存储结构完成。
[基本要求]
(1)依次从键盘或文件读入数据,建立线性表A和表B;
(2)输出两个线性表中的数据元素;
(3)求线性表A和表B的长度;
(4)取表A的第3个元素和修改表B的第6个元素15为14;
(5)实现在表A的第3个位置前插入元素6,删除原来第3个位置(插入操作后第4个为位置)元素8;
(6)将两个有序的线性表表A和表B合并成一个有序线性表(元素可以重复),测试数据经过上述修改后输出结果为2 3 5 6 6 8 9 11 11 14 20;
[测试数据]
ListA.txt文件内容如下:3 5 8 11
ListB.txt文件内容如下:2 6 8 9 11 15 20
#include <stdio.h>
using namespace std;
#include <fstream>
#include <iostream>
#define MAXSIZE 100
#define ERROR 0
typedef struct //线性表
{
int* elem;
int length;
}List;
void InitList(List& L) //初始化线性表
{
L.elem = new int[MAXSIZE];
L.length = 0;
}
void ListInput(List& L, char filename[]) //从文件中读取数据输入到线性表中
{
int i = 0;
fstream file;
file.open(filename);
if (!file)
{
cout << "未找到相关文件,无法打开!" << endl;
exit(ERROR);
}
while (!file.eof())
{
file >> L.elem[i];
i++;
}
L.length = i;
}
int ListLength(List L) //求线性表的长度
{
return L.length;
}
void GetElem(List L, int i, int &e) //取线性表的元素
{
*(&e) = L.elem[i-1];
}
bool LocateElem(List L, int e) //确定输入元素是否在线性表中
{
for (int i = 0; i < L.length; i++)
{
if (L.elem[i] == e)
{
return true;
}
}
return false;
}
void ListInsert(List& L, int i, int e) //在线性表中插入元素
{
for (int j = L.length; j >= i-1; j--)
{
L.elem[j + 1] = L.elem[j];
}
L.elem[i-1] = e;
L.length++;
}
void ListUpdate(List& L, int i, int e) //更换线性表中的元素
{
L.elem[i] = e;
}
void ListDelete(List& L, int i) //删除线性表中的元素
{
for (int j = i - 1; j < L.length; j++)
{
L.elem[j] = L.elem[j + 1];
}
L.length--;
}
void ListOutput(List L) //输出线性表的内容
{
for (int i = 0; i < L.length; i++)
{
printf("%d ", L.elem[i]);
}
}
void MergeList(List& LC, List LA, List LB) //将两个有序的线性表表A和表 B合并成一个有序线性表
{
LC.length = LB.length + LA.length;
for (int i = 0; i < LA.length; i++)
{
LC.elem[i] = LA.elem[i];
}
int k = 0;
for (int j = LA.length; j < LB.length + LA.length; j++)
{
LC.elem[j] = LB.elem[k];
k++;
}
int temp=0;
for(int i=0;i<LC.length;i++)
{
for(int j=0;j<LC.length-1-i;j++)
{
if(LC.elem[j]>LC.elem[j+1])
{
temp=LC.elem[j];
LC.elem[j]=LC.elem[j+1];
LC.elem[j+1]=temp;
}
}
}
}
int main() //主函数
{
List LA, LB;
List LC;
int e;
InitList(LA);
InitList(LB);
InitList(LC);
ListInput(LA, "ListA.txt");
ListOutput(LA);
ListInput(LB, "ListB.txt");
ListOutput(LB);
cout << "线性表LA的长度是:" << ListLength(LA) << "," << "线性表LB的长度是:" << ListLength(LB) << endl;
GetElem(LA, 3, e);
cout << "表A中第3个位置的元素值是:" << e << endl;
ListUpdate(LB, 5, 14);
cout << "已经将第6个元素值15修改为14,新的线性表LB内容如下:";
ListOutput(LB);
ListInsert(LA, 3, 6);
cout << "在表A的第3个位置前插入元素6,新的线性表LA内容如下:";
ListOutput(LA);
ListDelete(LA, 4);
cout << "删除表A中的第3个元素,新的线性表LA内容如下:";
ListOutput(LA);
MergeList(LC, LA, LB);
cout << "合并两个线性表LA和LB,并保持其元素有序性。合并后新的线性表LC内容如下:";
ListOutput(LC);
return 0;