单链表存储成绩实验

#ifndef LinkList_H
#define LinkList_H


template<class DataType>
struct Node
{
DataType data1;
char data2;
Node<DataType> *next;
};


template<class DataType>
class LinkList
{
public:
LinkList();
LinkList(DataType a[],char *n[],int m);
~LinkList();
int Locate(DataType x);
void Insert(int i,DataType x,char *n);
DataType Delete(int i);
void PrintList();
private:
Node<DataType> *first;
};

#endif

#include<iostream>
using namespace std;
#include"LinkList.h"


template<class DataType>
LinkList<DataType>::LinkList()


{
first=new Node<DataType>;
fitst->next=NULL;
}


template<class DataType>
LinkList<DataType>::LinkList(DataType a[],char *n[],int m)
{
Node<DataType> *r,*s;
first=new Node<DataType>;
r=first;
for(int i=0;i<m;i++)
{
s=new Node<DataType>;
s->data1=a[i];
s->data2=*n[i];
r->next=s;r=s;
}
r->next=NULL;
}


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


template<class DataType>
void LinkList<DataType>::Insert(int i,DataType x,char *n)
{
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->data1=x;s->data2=*n;
s->next=p->next;p->next=s;
}
}




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


template<class DataType>
int LinkList<DataType>::Locate(DataType x)
{
Node<DataType>*p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)return count;
p=p->next;
count++;
}
return 0;
}


template<class DataType>
void LinkList<DataType>::PrintList()
{
Node<DataType>*p=first->next;
while(p!=NULL)
{
cout<<p->data1<<p->data2<<" ";
p=p->next;
}
cout<<endl;
}


#include<iostream>
using namespace std;
#include"LinkList.cpp"


void main()
{
char *n[6]={"A","B","C","D","E","F"};
int r[6]={4,9,6,7,2,1};
LinkList<int>L(r,n,6);
cout<<"执行插入前的数据:"<<endl;
L.PrintList();
try
{
L.Insert(2,30,"G");
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"执行插入后的数据:"<<endl;
L.PrintList();
try
{
L.Delete(1);
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"执行删除后的数据:"<<endl;
L.PrintList();
}






猜你喜欢

转载自blog.csdn.net/Vring_Jan/article/details/80188171