1.建立一个由n个学生成绩的顺序表,n的大小由自己确定,每一个学生的成绩信息由自己确定,实现数据的对表进行插入、删除、查找等操作。分别输出结果。------用单链表来实现。
#include<iostream>
using namespace std;
struct Node
{
double data;
Node*next;
};
class stu
{
private:
Node*first;
int count;
public:
stu(double a[], int n);
~stu();
void Insert(int i, double x);
double Get(int i);
int Locate(double x);
double Delete(int i);
};
stu::stu(double a[], int n)
{
int i;
first = new Node; first->next = NULL;
for (i = 0; i < n; i++)
{
Node*s;
s = new Node; s->data = a[i];
s->next = first->next; first->next = s;
}
}
stu::~stu()
{
while (first != NULL)
{
Node*q;
q = first;
first = first->next;
delete q;
}
}
void stu::Insert(int i, double x)
{
Node*p;
p = first; count = 0;
while (p != NULL&&count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL) throw"位置";
else
{
Node*s;
s = new Node; s->data = x;
s->next = p->next; p->next = s;
}
}
double stu::Get(int i)
{
Node*p;
p = first->next; count = 1;
while (p != NULL&&count < i)
{
p = p->next;
count++;
}
if (p == NULL) throw"位置";
else return p->data;
}
int stu::Locate(double x)
{
Node*p;
p = first->next; count = 1;
while (p != NULL)
{
if (p->data == x) return 7-count;
p = p->next;
count++;
}
return 0;
}
double stu::Delete(int i)
{
Node*p;
p = first; count = 0;
while (p != NULL&&count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL || p->next == NULL) throw"位置";
else
{
Node*q; double x;
q = p->next; x = q->data;
p->next = q->next;
delete q;
return x;
}
}
int main()
{
double a[10] = { 91,92,93,94,95,96 };
stu student(a, 6);
student.Insert(2, 100);
student.Delete(6);
cout<<student.Get(2)<<endl;
cout<<student.Locate(96)<<endl;
}