《数据结构》实验二: 线性表实验

来源:互联网 发布:神州科捷工作知乎 编辑:程序博客网 时间:2024/05/20 16:09

《数据结构》实验二:     线性表实验

一..实验目的

     巩固线性表的数据结构,学会线性表的应用。

1.回顾线性表的逻辑结构,线性表的物理存储结构和常见操作。

2.学习运用线性表的知识来解决实际问题。

3.进一步巩固程序调试方法。

4.进一步巩固模板程序设计。

二.实验时间

   准备时间为第2周到第4周,具体集中实验时间为第4周第2次课。2个学时。

三..实验内容

1.建立一个N个学生成绩的顺序表,对表进行插入、删除、查找等操作。分别输出结果。

要求如下:

用顺序表来实现。

头文件

 

 

#ifndef shunxu_h
#define shunxu_h

const  int max = 100;
template<class datatype>
class shunxu
{
public:
 shunxu(){ length = 0; }
 shunxu(datatype a[],int n);
 void insert(datatype x, int n);
 int delet(int n);
 int locat(int n);
 void print();


private:

 int data[max];
 int length;
   
};

template<class datatype>
shunxu<datatype>::shunxu(datatype a[], int n)
{

 if (n > max)throw "error";
 if (n < 1)throw"位置异常";
 for (int i = 0; i < n; i++)
 {
  data[i] = a[i];
 }
 length = n;
}

template<class datatype>
void shunxu<datatype>::insert(datatype x, int n)
{
 int j;
 if (length > max)throw "error";
 if (n<1 || n>length + 1)throw"输入错误";
 for (j = length; j >= n; j--)
  data[j] = data[j - 1];
 data[n - 1] = x;
 length++;


}

template<class datatype>
int shunxu<datatype>::delet(int n)
{

 int x = data[n - 1];//怎么把位置清空
 for (int j= n-1; j < length; ++j)
  data[j] = data[j+1];
 
 length--;
 return x;
 
}

template<class datatype>
int shunxu<datatype>::locat(int n)
{
 int j;
 for (j = length - 1; data[j] != n; j--);

 if (data[j] == n)
  cout << "输入的元素位置是:" << j + 1 << endl;
 
 return 0;
}

template<class datatype>
void shunxu<datatype>::print()
{
 for (int j = 0; j < length; j++)
  cout << data[j] << "  ";
 cout<<endl;
}


#endif

 

 

主函数

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

 


void main()
{
 int y,g;
 int a[] = { 5, 6, 7, 8, 9, 15, 16 };

 shunxu<int> s(a, 7);
 cout << "输入的数据为:" << endl;
 s.print();
 cout << "插入一个新元素2在第三的位置上" << endl;
 s.insert(2, 3);
 s.print();
 cout << "删除第二个数据后,信息为:"<<endl;
 s.delet(2);
 s.print();
 cout << "查找某个元素的位置,输入要查找的元素:"<<endl;
 cin >> g;
    s.locat(g);
 cin >> y;
 
}

 

 

构造函数和插入操作

 

删除、查找,定位等操作代码

 

 

主函数调用时

 

 

 

 

 

插入数据:

 

 

删除第二个数据后

 

查找元素

 

0 0