第十四周实验报告2

来源:互联网 发布:光之教堂数据 编辑:程序博客网 时间:2024/05/11 11:37

* (程序头部注释开始)

 * 程序的版权和版本声明部分

 * Copyright (c) 2011, 烟台大学计算机学院学生 

 * All rights reserved.

 * 文件名称:建立专门的数组类处理有关数组的操作

* 作    者:        任小宁                

 * 完成日期:     2012    年 5    月 21

 * 版 本 号:      201158504431

 * 对任务及求解方法的描述部分

#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->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);  }void MyList::cat(MyList &il) //将链表il连接到当前对象的后面{Student *ss=head;while(ss->next != NULL)      {          ss = ss->next;      }  ss->next=il.head;}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;while(s->next != NULL)      {  cout<<"num="<<s->num<<"score="<<s->score<<'\t';        s = s->next; ++length;    } 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<<"head1: "<<endl; //输出head1head1.display();MyList head2(1001,98.4);  //建立head2链表head2.append(1002,73.5);  //通过“追加”的方式增加结点head2.append(1003,92.8);head2.append(1004,99.7);cout<<"head2: "<<endl;   //输出head2head2.display();head2.cat(head1);   //反head1追加到head2后面cout<<"length of head2 after cat: "<<head2.length()<<endl;cout<<"head2 after cat: "<<endl;   //显示追加后的结果head2.display();system("pause");return 0;}输出结果:input head1:2312323.5434532450452345.0453head1:num=4532450score=452345 num=123score=23.543     head2:num=1001score=98.4      num=1002score=73.5      num=1003score=92.8      length of head2 after cat: 6head2 after cat:num=1001score=98.4      num=1002score=73.5      num=1003score=92.8      num=1004score=99.7      num=4532450score=452345 num=123score=23.543     请按任意键继续.