实验三:用双链表实现

#include<iostream.h>
const int MaxSize=100;
struct Node
{
 int data;
 Node *next;
 Node *prior;
};
class Student
{
public:
 Student();
 Student(int a[],int n);
 ~Student();
 static int count;
 int Length();
 void Insert(int i,int x);
 int Delete(int i); 
 int Get(int i);
 int Locate(int x);
 void Print();
private:
 Node *first;
 int length;
};
int Student::count=0;
Student::Student(int a[],int n)
{
 int i;
 Node *s;
 length=0;
 first=new Node;
 first->next=NULL;
 first->prior=NULL;
 for(i=0;i<n;i++)
 {
      s=new Node;
  s->data=a[i];
  s->next=first->next;
  first->next=s;
 }
}
Student::~Student()
{
 Node *q;
    q=first;
 while(first->next!=first->prior)
 {
  delete q;
  q=q->next;
 }
}
int Student::Length()

     Node *p;
     p=first->next;   
     count=0;   
     while(p!=NULL) 
     {   
         p=p->next;   
         count++;   
      }   
     return length; 
 }
void Student::Insert(int i,int x)
{
 Node *p,*s;
 p=first;
 count=0;
 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;
 }
}
int Student::Delete(int i)
{
 int x;
 Node *p,*q;
 p=first->next;count=1;
 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;
 }
}
int Student::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 Student::Locate(int x)
{
 Node *p;
 p=first->next;count=1;
 while(p!=NULL)
 {
  if(p->data==x) return count;
  p=p->next;
  count++;
 }
 return 0;
}
void Student::Print()
{
 Node *p;
 p=first->next;
 while(p->next!=NULL)
 {
  cout<<p->data<<" ";
  p=p->next;
 }
 cout<<p->data<<endl;
}
void main()
{
 int score[5]={60,65,70,80,85};
 Student S(score,5);
 cout<<"学生的体育成绩:"<<endl;
 S.Print();
 cout<<endl<<endl<<"在位置3插入成绩75,结果如下:"<<endl;
 S.Insert(3,75);
 S.Print();
    cout<<endl<<endl<<"在位置6删除成绩为:"<<S.Delete(6)<<endl;
 cout<<"删除后结果如下:"<<endl;
 S.Print();
 cout<<endl<<endl<<"位置4的成绩为:"<<S.Get(4)<<endl;
 cout<<endl<<endl<<"成绩65所在的位置为:"<<S.Locate(65)<<endl;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值