实验A—1 顺序表基本操作

来源:互联网 发布:java 中文字符 编辑:程序博客网 时间:2024/06/06 04:43
内容:

建立n个元素的顺序表,实现相关的操作:输出,插入,删除,查找等功能。

操作:

本题意在熟悉顺序表的基本操作,故不进行额外功能拓展,仅实现列出功能。

以下为实现代码:

头文件LINKLIST.h:

#pragma onceconst int Max = 10;class Sqlist {private:int length;int data[Max];public:Sqlist() { length = 0; }   //0表Sqlist(int A[], int n);    //n表void Output();             //输出void Insert(int i, int x); //插入int Delete(int i);         //删除void Search(int i);        //指向查找void Locate(int x);        //数值查找};
类函数功能cpp文件:

#include"LINKLIST.h"#include<iostream>using namespace std;Sqlist::Sqlist(int A[], int n) {if (n > Max)throw"invalid parameter";for (int i = 0; i < n; i++)data[i] = A[i];length = n;}void Sqlist::Output() {for (int i = 0; i < length; i++)cout << data[i] << "\t";}void Sqlist::Insert(int i, int x) {if (length > Max + 1)throw"overflow";if (i<1 || i>length + 1)throw"location";for (int j = length; j > i - 1; j--)data[j] = data[j - 1];data[i] = x;length++;}int Sqlist::Delete(int i) {if (length == 0)throw"overflow";if (i<1 || i>length)throw"location";int x = data[i - 1];for (int j = i; j < length; j++)data[j - 1] = data[j];length--;return x;}void Sqlist::Search(int i ){if (!(i > 0 && i < length + 1))throw"invalid parameter";elsecout << "Finding element is:"<< data[i - 1] << endl;}void Sqlist::Locate(int x) {for (int i = 0; i < length; i++)if (data[i] == x)cout << "Location is:" << i + 1 << endl;}
测试代码:

#include"LINKLIST.h"#include<iostream>using namespace std;int Test() {int arr[10] = { 3,2,1,6,5,4,9,8,7,0 };Sqlist s(arr, 10);cout << "Normal: ";s.Output();cout << endl<<"Insert: ";s.Insert(3, 11);s.Output();cout << endl<<"Deleted:";s.Delete(3);s.Output();cout << endl << endl;s.Search(1);s.Locate(0);cout << endl;return 0;}void main() {Test();}

理论运行结果:

          Normal3   2   1   6   5   4   9   8   7   0

          Insert3   2   1   11   6   5   4   9   8   7   0

          Deleted: 3   2   11   6   5   4   9   8   7   0

 

          Finding element is3

          Location is10


实际运行结果:



二者一致,代码成功实现。


总结:

       在基本操作这一块基本并没有遇到太大的问题,编译也是一次通过,没有进行debug。个人方面,在进行简单逻辑语句判断时所需时间还是比较长。