您的位置:首页 > 其它

实验一:线性表实验-顺序表的实现

2017-09-26 00:40 253 查看
1.实验前的概念理解:

线性表(linear list):是数据结构的一种,一个线性表是n个具有相同特性的数据元素的有限序列。(是一种逻辑结构,可以自由的删除或添加结点,而受限线性表(栈和队列)对结点的操作受限)

顺序表:在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。

2.实验目的:

(1)掌握线性表的顺序储存结构;

 (2)验证顺序表及其基本操作的实现;

(3)理解算法与程序的关系,能够将顺序表算法转换为对应的程序。

3.实现内容

(1)建立含有若干个元素的顺序表;

(2)分别用C++和javascript对已建立的顺序表实现插入、删除、查找等基本操作;

(3)对比两种语言。

4.C++实现和javaScript实现

4.1.C++实现

由于线性表的数据元素类型不确定,所以采用C++的模板机制,首先定义一个模板类

//SeqList.h  
头文件                        

ifndef SeqList_H
#define SeqList_H
const int MaxSize = 10;
class SeqList {
public:
SeqList() { length = 0; };
SeqList(int a[], int n) ;
~SeqList() {};
void Insert(int i, int x);
int Delete(int i);
int Locate(int x);
void PrintList();
private:
int data[MaxSize];
int length;
};
#endif





//SeqList.cpp   源文件的功能实现函数                     

#include<iostream>
using namespace std;
#include "SeqList.h"

SeqList::SeqList(int a[], int n)
9190
{
if (n > MaxSize) throw"非法参数";
for (int i = 0; i < n; i++)
data[i] = a[i];
length = n;
}

void SeqList::Insert(int i, int x) {
if (length >= MaxSize) throw"上溢";
if (i<1 || i>length + 1) throw"位置非法";
for (int j = length; j >= i; j--)
data[j] = data[j - 1];
data[i - 1] = x;
length++;
}
int SeqList::Delete(int i) {
if (length == 0)throw"下溢";
if (i<1 || i>length)throw"位置非法";
int x = data[i - 1];
for (int j = i; j < length; j++)
data[j - 1] = data[j];
length--;
return x;
}

int SeqList::Locate(int x) {
for (int i = 0; i < length; i++)
if (data[i] == x) return i + 1;
return 0;
}

void SeqList::PrintList() {
for (int i = 0; i < length; i++)
cout << data[i] << "";
cout << endl;
}


//SeqList.main.cpp
源文件的主函数

#include <iostream>
using namespace std;
#include"SeqList.h"

void main() {
int r[5] = { 1,2,3,4,5 };
SeqList L(r, 5);
cout << "执行插入操作前数据为:" << endl;
L.PrintList();
try {
L.Insert(2, 3);
}
catch (char *s) {
cout << s << endl;
}
cout << "执行插入操作后数据为:" << endl;
L.PrintList();
cout << "值为3的元素位置为:";
cout << L.Locate(3) << endl;
cout << "执行删除第一个元素操作,删除前数据为:" << endl;
L.PrintList();
try {
L.Delete(1);
}
catch(char *s){
cout << s << endl;
}
cout << "删除后数据为:" << endl;
L.PrintList();
}


//实验结果




4.2.JavaScript实现

时间不太够,之后补
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: