头文件
#ifndef LinkList_H
#define LinkList_H //if not defined,防止头文件的重复包含和编译
template <class student> //定义单链表的结点
struct Node
{
student data;
Node <student>*next;
};
//以下是类LinkList的声明
template <class student>
class LinkList
{
public:
LinkList();
LinkList(student a[],int n);
~LinkList();
int Locate(student x);
void Insert(int i,student x);
student Delete(int i);
void PrintList();
private:
Node<student>*first;
};
#endif
源文件
#include <iostream>
using namespace std;
#include "LinkList.h"
template<class student>
LinkList<student>::LinkList()
{
first=new Node<student>;
first->next=NULL;
}
template<class student>
LinkList<student>::LinkList (student a[],int n)
{
Node<student>*r,*s;
first=new Node<student>;
r=first;
for(int i=0;i<n;i++)
{
s=new Node<student>;
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
template<class student>
LinkList<student>::~LinkList()
{
Node<student>*q=NULL;
while(first!=NULL)
{
q=first;
first=first->next;
delete q;
}
}
template<class student>
void LinkList<student>::Insert(int i,student x)
{
Node<student>*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<student>;s->data=x;
s->next=p->next;p->next=s;
}
}
template<class student>
student LinkList<student>::Delete(int i)
{
Node<student>*p=first,*q=NULL;
student 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->data;
p->next=q->next;
delete q;
return x;
}
}
template<class student>
int LinkList<student>::Locate(student x)
{
Node<student>*p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x) return count;
p=p->next;
count++;
}
return 0;
}
template<class student>
void LinkList<student>::PrintList()
{
Node <student>*p=first->next;
while(p!=NULL)
{
cout<<p->data<<"";
p=p->next;
}
cout<<endl;
}
源文件主函数
#include <iostream>
using namespace std;
#include "LinkList.cpp"
void main()
{
int r[5]={95,68,75,98,79};
LinkList<int>L(r,5);
cout<<"5个学生的成绩分别是:"<<endl;
L.PrintList();
cout<<"李华成绩为85"<<endl;
try
{
L.Insert(2,85);
}
catch (char *s)
{
cout<<s<<endl;
}
cout<<"将李华的成绩插入到第二个后成绩为;"<<endl;
L.PrintList();
cout<<"成绩为85的学生排在:";
cout<<L.Locate(85)<<endl;
cout<<"删除第二个学生的成绩前,所有学生成绩分别为:"<<endl;
L.PrintList();
try
{
L.Delete(2);
}
catch (char *s)
{
cout<<s<<endl;
}
cout<<"删除后所有的学生成绩分别为:"<<endl;
L.PrintList();
system("pause");
}
调试后结果
不明白为什么输出的分数之间没有空格,求解求解求解。