数据结构实验二之单链表

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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值