双链表建立学生成绩

#include <iostream>
using namespace std;  
const int M=100;  
struct Node  
{  
        int data;  
        Node *next,*prior;   
};
class LinkList              
{  
    public:  
        LinkList();  
        LinkList(int  a[],int n);  
        ~LinkList();  
        int Length();               //表长   
        int Get(int i);              //按位查找   
        void Input(int i,int x);    //插入   
        int Delete(int i);           //删除   
        void Print();          //遍历操作   
    private:  
        Node *first;      
};  


LinkList::LinkList()  
{     
    first=new Node;  
    first->next=NULL;      
}  


LinkList::LinkList(int a[],int n)  
{     
    Node *r;  
    Node *s;  
    int i;  
    first=new Node;  
    r=first;  
    for(i=0;i<n;i++)  
    {  
        s=new Node;s->data=a[i];  
        r->next=s;r=s;  
    }  
    r->next=NULL;       
}  
LinkList::~LinkList()  
{  
    while(first!=NULL)  
    {     
        Node *q;  
        q=first;  
        first=first->next;  
        delete q;  
    }  
}  
int LinkList::Length()    
{  
    Node *p;  
    int count;  
    p=first->next; count=0;  
    while(p!=NULL)  
    {  
        p=p->next;  
        count++;  
    }  
    return count;  
}  
int LinkList::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 return p->data;    
}  
    void LinkList::Input(int i,int x)   
{  
    Node *p;  
    int count;  
    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->prior = p;
        s->next = p->next;
        p->next->prior = s;
        p->next = s;
        }   
}  
  
int LinkList::Delete(int i)  

    Node *p;  
    Node *q;  
    int x;  
    int count=0;  
    p=first;q=NULL;  
    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;
        (q->next)->prior = p->prior;
        delete q;  
        return x;  


    }   
}  


void LinkList::Print()    
{  
    Node *p;  
    int i=0;      
    p=first->next;  
    while(p!=NULL)  
    {     
        i=i+1;   
        cout<<"第"<<i<<"个学生成绩:"<<p->data<<endl;
        p=p->next;  
    }  
}  
 
void main()
{
int r[5]={80,90,70,60,50};
LinkList L(r,5);
cout<<"录入学生信息:"<<endl;
L.Print();
cout<<endl;
cout<<"在第2个位置插入85"<<endl;
L.Input(2,85);
cout<<"插入后学生成绩为:"<<endl;
L.Print();
cout<<endl;
cout<<"第三位学生成绩为:"<<endl;
cout<<L.Get(3)<<endl;
cout<<"删除第二个学生成绩"<<endl;
L.Delete(2);
cout<<"删除后学生成绩为:"<<endl;

L.Print();}




猜你喜欢

转载自blog.csdn.net/CHENCHWT/article/details/80148858