实验三 用双链表实现学生成绩管理系统

#include<iostream>
using namespace std;
//template<class DataType>
typedef int DataType;
struct Node
{
	DataType data;
	struct Node *next;
};


//template<class DataType>
class Linklist
{
	public:
		Linklist();
		Linklist(DataType a[],int n);
		~Linklist();
		int Length();
		DataType Get(int i);
		int Locate(DataType x);
		void Insert(int i,DataType x);
		DataType Delete(int i);
		void Printlist();
	private:
		struct Node *first;
};


//template<class DataType>
void Linklist::Printlist()    
{  
    Node *p;  
    int i=0;      
    p=first->next;  
    while(p!=NULL)  
    {     
        i=i+1;   
        cout<<"第"<<i<<"个学生成绩:"<<p->data<<endl;
        p=p->next;  
    }  
}  


//template<class DataType>
int Linklist::Length()
{
	struct Node *p;
	p=first->next;
	int count=0;
	while(p!=NULL)
	{
		p=p->next;
		count++;
	}
	return count;
}


//template<class DataType>
DataType Linklist::Get(int i)
{
	struct Node *p;
p=first->next;
	int count=1;
	while(p!=NULL&&count<i)
	{
		p=p->next;
		count++;
	}
	if(p==NULL)		
		cout<<"位置"<<endl;
	else  cout<<p->data<<endl;		
	return 0;
}


//template<class DataType>
int Linklist::Locate(DataType x)
{
	struct Node *p;
	p=first->next;
	int count=1;
	while(p!=NULL)
	{
		if(p->data==x){
			cout<<count<<endl; 
			return 1; 
		} 	
		p=p->next;
		count++;
	}
	cout<<"无此成绩"<<endl; 
	return 0;
}


//template<class DataType>
void Linklist::Insert(int i,DataType x)
{
	struct Node *p,*s;
	p=first;
	int count=0;
	while(p!=NULL&&count<i-1)
	{
		p=p->next;
		count++;
	}
	if(p==NULL)
	cout<<"位置"<<endl;
	else
	{
		s=new Node;
		s->data=x;
		s->next=p->next;
		p->next=s;
	}
}


//template<class DataType>
Linklist::Linklist()
{
	first=new Node;
	first->next=NULL;
}


//template<class DataType>
Linklist::Linklist(DataType a[],int n)
{
	struct 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;
	}
}


//template<class DataType>
DataType Linklist::Delete(int i)
{
	struct Node *p,*q;
	p=first;
	int count=0,x;
	while(p!=NULL&&count<i-1)
	{
		p=p->next;
		count++;
	}
	if(p==NULL||p->next==NULL)
		cout<<"位置"<<endl;
	else
	{
		q=p->next;
		x=q->data;
		p->next=q->next;
		delete q;
		return x;
	}
	return 0;
}


//template<class DataType>
Linklist::~Linklist()
{
	struct Node *q;
	while(first!=NULL)
	{
		q=first;
		first=first->next;
		delete q;
	}
}


//template<class DataType>
int main()
{
	cout<<"单链表实现学生成绩"<<endl;	int score[3]={77,88,99};
	Linklist L(score,3);
	cout<<"学生的数据结构成绩为:"<<endl;
	L.Printlist();
	cout<<endl<<endl<<"在位置2插入成绩66:"<<endl;
	L.Insert(2,66);
	L.Printlist();
	cout<<endl<<endl<<"在位置1删除:"<<endl;
	L.Delete(1);
	L.Printlist();
	cout<<endl<<endl<<"位置3的成绩为:"<<endl;
	L.Get(3);
	cout<<endl<<endl<<"成绩为88所在的位置为:"<<endl;
	L.Locate(88);	
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/nika_jy_L/article/details/80344364