实验三 单链表

#include<iostream.h>
template<class DataType>
struct Node
{
 DataType grade;
 Node<DataType>*next;
};
template<class DataType>
class Student
{
public:
 Student();
 Student(DataType g[],int n);
 ~Student();
 int locate(DataType x);
 void insert(int i,DataType x);
 DataType Delete(int i);
 void printlist();
private:
 Node<DataType>*first;
};
template<class DataType>
Student<DataType>::Student()
{
 first=new Node<DataType>;
 first->next=NULL;
}
template<class DataType>
Student<DataType>::Student(DataType g[],int n)
{
 Node<DataType>*r,*s;
 first=new Node<DataType>;
 r=first;
 for(int i=0;i<n;i++)
 {
  s=new Node<DataType>;
  s->grade=g[i];
  r->next=s;r=s;
 }
 r->next=NULL;
}
template<class DataType>
Student<DataType>::~Student()
{
 Node<DataType>*q=NULL;
 while(first!=NULL)
 {
  q=first;
  first=first->next;
  delete q;
 }
}
template<class DataType>
void Student<DataType>::insert(int i,DataType x)
{
 Node<DataType>*p=first,*s=NULL;
 int count=0;
 while(p!=NULL&&count<i-1)
 {
  p=p->next;
  count++;
 }
 if(p==NULL)throw"位置非法";
 else{
  s=new Node<DataType>;s->grade=x;
  s->next=p->next;p->next=s;
 }
}
template<class DataType>
DataType Student<DataType>::Delete(int i)
{
 Node<DataType>*p=first,*q=NULL;
 DataType g;
 int count=0;
 while(p!=NULL&&count<i-1)
 {
  p=p->next;
  count++;
 }
 if(p==NULL||p->next==NULL)
  throw"位置非法";
 else{
  q=p->next;g=q->grade;
  p->next=q->next;
  delete q;
  return g;
 }
}
template<class DataType>
int Student<DataType>::locate(DataType x)
{
 Node<DataType>*p=first->next;
 int count=1;
 while(p!=NULL)
 {
  if(p->grade==x)return count;
  p=p->next;
  count++;
 }
 return 0;
}
template<class DataType>
void Student<DataType>::printlist()
{
 int i=0;
 Node<DataType>*p=first->next;
 while(p!=NULL)
 {
  i=i+1;
  cout<<"第"<<i<<"个学生成绩:";
  cout<<p->grade<<" ";
  p=p->next;
  cout<<endl;
 }
 cout<<endl;
}
void main()
{
 int g[5]={99,95,91,88,94};
 Student<int>S(g,5);
 cout<<"执行插入操作前学生的成绩为:"<<endl;
 S.printlist();
 try
 {
  S.insert(2,70);
 }
 catch(char *s)
 {
  cout<<s<<endl;
 }
 cout<<"插入第二个学生成绩后的数据为:"<<endl;
 S.printlist();
 cout<<"成绩为88的学生位置为:";
 cout<<S.locate(88)<<endl;
 cout<<"执行删除第一个学生成绩前的数据为:"<<endl;
 S.printlist();
 try
 {
  S.Delete(1);
 }
 catch(char *s)
 {
  cout<<s<<endl;
 }
 cout<<"执行删除第一个学生成绩后的数据为:"<<endl;
 S.printlist();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值