实验三.2单链表

#include<iostream>
using namespace std; 
const int MaxSize=100;
struct Node
{
float data;
Node *next;
};
class Student
{
public:
Student();
Student(float a[],int n);
int Get(int i);
void Insert(int i,float x);
float Locate(float x);
float Delete(int i);
void Print();
~Student();
private:


Node *first;
};
Student::Student()
{
first=new Node;
first->next=NULL;
}
Student::Student(float a[],int n)
{
Node *s;
first=new Node;
first->next=NULL;
for(int i=0;i<n;i++)
{
s=new Node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
int Student::Get(int i)
{
Node *p;
int count;
p=first->next;
count=1;
while(p!=NULL&&count<i)
{
p=p->next;
count ++;
}
if(p==NULL)
throw"位置非法";
else 
cout<<p->data<<endl ;
return 0;
}
void Student::Insert(int i,float x)
{
Node *p,*s;
int count=0;
p=first;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL)throw"位置非法";
else
{
s=new Node;
s->data=x;
s->next=p->next;
p->next=s;
}
}
float Student::Locate(float x)
{
Node *p;
int count=1;
p=first->next;
while(p!=NULL)
{
if(p->data==x)return count;


p=p->next;
count++;
}
return 0;
}
float Student::Delete(int i)
{
Node *q,*p;
p=first;
float x;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)throw"位置";
else
{
q=p->next;
x=q->data;
p->next=q->next ;
delete q;
return x;
}
return 0;
}
void Student::Print()
{
Node *p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
Student::~Student()
{
Node *q;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
int main()
{
float a[4]={50,87,66.5,69};
Student stu(a,4);
cout<<"学生的成绩为:"<<endl;
stu.Print();
cout<<"位置4的成绩为:"<<endl;
stu.Get(4);
cout<<"在位置3插入成绩90后的结果为:"<<endl;
stu.Insert(3,90);
stu.Print();
cout<<"删除位置2的成绩后的结果为:"<<endl;
stu.Delete(2);
stu.Print();cout<<"成绩50所在的位置为:"<<endl;
stu.Locate(50);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值