您的位置:首页 > 理论基础 > 数据结构算法

《数据结构》实验二:线性表的实验(顺序表)

2014-10-19 20:41 225 查看
一..实验目的
巩固线性表的数据结构,学会线性表的应用。
1.回顾线性表的逻辑结构,线性表的物理存储结构和常见操作。
2.学习运用线性表的知识来解决实际问题。
3.进一步巩固程序调试方法。
4.进一步巩固模板程序设计。
二.实验时间
准备时间为第2周到第4周,具体集中实验时间为第4周第2次课。2个学时。
三..实验内容
1.建立一个N个学生成绩的顺序表,对表进行插入、删除、查找等操作。分别输出结果。
要求如下:
1)用顺序表来实现。
2)用单链表来实现。
顺序表源代码:
头文件Head.h:
#ifndef head_H

#define head_H

const int N=50;

class Student

{

public:

Student(){length=0;}

Student(int a[],int n);

~Student(){};

void insert(int i,int x);

int del(int i);

int locate(int x);

void print();

private:

int data
;

int length;

};

#endif

Student_func.cpp:

#include<iostream>

#include"head.h"

using namespace std;

Student::Student(int a[], int n)

{

if(n>N) throw "parameter illegal";

for(int i=0;i<n;i++)

data[i]=a[i];

length=n;

}

void Student::insert(int i, int x)

{

if(length>=N) throw "overflow";

if(i<1||i>length+1) throw "location illegal";

for (int j = length; j >= i; j--)

data[j] = data[j - 1];

data[i - 1] = x;

length++;

}

int Student::del(int i)

{

if (length==0) throw "underflow";

if(i<1||i>length+1) throw "location illegal";

int x=data[i-1];

for(int j=i;j<length;i++)

data[j-i]=data[j];

length--;

return x;

}

int Student::locate(int x)

{

for(int i=0;i<length;i++)

if(data[i]==x)return i+1;

return 0;

}

void Student::print()

{

cout << "所有学生成绩如下:";

for(int i=0;i<length;i++)

cout<<data[i]<<" ";

cout<<endl;

}

Student_main.cpp:

#include<iostream>

#include<iomanip>

#include<stdlib.h>

#include"head.h"

using namespace std;

int main()

{

int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };

Student S(arr, 10);

while (1)

{

system("cls");

cout << "输入数字实现相应功能:" << endl;

cout << "1.显示全部学生成绩" << endl;

cout << "2.插入学生成绩" << endl;

cout << "3.查找学生成绩" << endl;

cout << "4.删除学生成绩" << endl;

cout << "0.退出程序" << endl;

int choose;

cout << "输入选择项:"; cin >> choose;

if (choose == 0) break;

switch (choose)

{

case 1:S.print();

system("pause");

break;

case 2:

int n; int x;

cout << "输入要插入到的位置:";

cin >> n;

cout << "要插入的成绩:"; cin >> x;

try

{

S.insert(n, x);

}

catch (char *s)

{

cout << s << endl;

}

cout << "插入后的所有学生成绩为:" << endl;

S.print();

system("pause");

break;

case 3:

int y;

cout << "输入要查找的成绩:";

cin >> y;

cout << "值为"<<y<<"的元素位置为:"

<<S.locate(y)<<endl;

system("pause");;

break;

case 4:

int z;

cout << "输入要删除的位置:"; cin >> z;

try

{

S.del(z);

}

catch (char *s)

{

cout << s << endl;

}

cout << "删除后的数据为:" << endl;

S.print();

system("pause");

break;

default:cout << "选择项无效!";

}

}

system("pause");

return 0;

}







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