#include<iostream>
using namespace std;
class Student
{
public:
Student(int n,double s){num=n;score=s;next=NULL;}
Student *next;
int num;
double score;
};
class MyList
{
public:
MyList(){head=NULL;}
MyList(int n,double s){head=new Student(n,s);} //以Student(n,s)作为单结点的链表
int display(); //输出链表,返回值为链表中的结点数
void insert(int n,double s); //插入:将Student(n,s)结点插入链表,该结点作为第一个结点
void append(int n,double s); //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点
void cat(MyList &il); //将链表il连接到当前对象的后面
int length(); //返回链表中的结点数
private:
Student *head;
};
void MyList::insert(int n,double s) //插入:将Student(n,s)结点插入链表,该结点作为第一个结点
{
Student *ss=head;
head=new Student(n,s);//此时head位置改变
head->next=ss;
}
void MyList::append(int n,double s) //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点
{
Student *ss=head;
while((ss->next )!= NULL)
{
ss =ss->next;
}
ss->next=new Student(n,s); //直到ss->null时,将后面再链上一个结点
}
void MyList::cat(MyList &il) //将链表il连接到当前对象的后面
{
Student *ss=head;
while(ss->next != NULL)
{
ss = ss->next;
}
ss->next=il.head;//此时ss->next已不为null,然后再进行循环
cout<<endl;
}
int MyList::length() //返回链表中的结点数
{
int length=0;
Student *s=head;//指向链表开头的
while(s->next != NULL)
{
s = s->next;
++length;
}
return length;
}
int MyList::display() //输出链表,返回值为链表中的结点数
{
Student *s=head;
int length=0;
if(head==NULL)
{
cout<<"empty"<<endl;
return 0; //没有结点
}
while(s)
{
++length;
cout<<"num"<<s->num<<" "<<"score"<<s->score<<endl;
s=s->next;
}
return length;
}
int main()
{
int n;
double s;
MyList head1;
cout<<"input head1: "<<endl; //输入head1链表
for(int i=0;i<3;i++)
{
cin>>n>>s;
head1.insert(n,s); //通过“插入”的方式
}
cout<<endl;
cout<<"head1: "<<endl; //输出head1
head1.display();
MyList head2(1001,98.4); //建立head2链表
head2.append(1002,73.5); //通过“追加”的方式增加结点
head2.append(1003,92.8);
head2.append(1004,99.7);
cout<<endl;
cout<<"head2: "<<endl; //输出head2
head2.display();
head2.cat(head1); //反head1追加到head2后面
cout<<"length of head2 after cat: "<<head2.length()<<endl;
cout<<endl;
cout<<"head2 after cat: "<<endl; //显示追加后的结果
head2.display();
cout<<endl;
system("pause");
return 0;
}
总结
这个任务相对来说还可以 ,因为陈老师刚给我们上过链表这一节,对此印象也比较深刻,做起来也相对比较容易一些。。