Experiment 3 Single Linked List Realizes Student Achievement Management

Code:

#include<iostream>

using namespace std;
struct node
{
float data;
node* next;
};
class student
{
node* first,*p,*q;
public:
student();
student(float a[],int n); //create n A singly linked list of elements
~student();
int leng(); //find the length of the singly linked list
float get(int i); //find by bit, find the element value of the i-th node
int locate(float x) ; //Search by value
void insert(float x,int i); //Insert operation, insert a node with element value x at the i-th position
float dele(int i); //Delete operation, delete the i-th Node
void print(); //Iterate through all elements
};
student::student()
{first=new node;
first->next=NULL;
}
student::student(float a[],int n) //
{first=new node;first->next=NULL;
for(int i=0;i<n;i++)
{
node* s=new node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
student::~student()   //
{
while(first!=NULL)
{q=first;
first=first->next;
delete q;}
}


int student::leng()  //返回单链表的长度
{p=first->next;int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
float student::get(int i)   //
{
p=first->next;int count=1;
while(p!=NULL&&count<i)
{p=p->next;
count++;
}
if(p==NULL) throw "location error";
else return p->data;
}
int student::locate(float x)
{p=first->next;int count=1;
while(p! =NULL)
{
if(p->data==x) return count; //The search is successful, and the function number is returned
p=p->next;
count++;
}
return 0;
} //Exit the loop to indicate that the search failed
void student:: insert(float x,int i) //Head insertion
{p=first->next;int count=1;
while(p!=NULL&&count<i-1)
{p=p->next;
count++;
}
if( p==NULL) throw "Incorrect insertion position";
else {
node* s=new node;
    s->data=x;
s->next=p->next;
p->next=s;
}
}
float student::dele(int i)     //
{p=first;int count=0;
while(p!=NULL&&count<i-1)      //找到第i个结点
{
p=p->next;count++;
}
if(p==NULL||p->next==NULL)  throw"位置";
else {
float x;
q=p->next;x=q->data;
p->next=q->next;
delete q;
return x;
}}
void student::print()
{p=first->next;
while(p!=NULL)
{cout<<p->data<<"\t";
p=p->next;
}
}
void main()
{
float a[7]={89,88,87.5,86,85,84,83};
student s(a,7);
cout<<"**********************\n"<<"The singly linked list realizes the operation of student grades\n"<<"************************\n";
cout<<"Total"<<s.leng()<<"Student grades"<<endl;
s.print();
cout<<"Insert grades of 90 students into the 4th place"<<endl;
try{
s.insert(90,4);}
catch(char *s)
{
cout<<s<<endl;}
cout<<"Insert the 89th grade into the 10th place";
try{
s.insert (89,10);}
catch(char *s)
{
cout<<s<<endl;}
s.print();
try{
cout<<"Find the 6th grade value: "<<s.get( 6)<<endl;
}
catch(char *s)
{
cout<<s<<endl;}
try{
cout<<"Delete the element value in position 5"<<s.dele(5)<<endl; }
catch(char *s)
{
cout<<s<<endl;}
s.print();
cout<<"The one with a score of 88 is the "<<s.locate(88)<<" bit"<< endl;

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325611543&siteId=291194637