第十四周实验报告(二)

来源:互联网 发布:淘宝首页图片轮播尺寸 编辑:程序博客网 时间:2024/06/04 23:34

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 作 者:李冠绩
* 完成日期: 2012 年5月28日
* 版 本 号: V1.0
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 程序头部的注释结束

 

#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;
};

int MyList::display()
{
 if(head==NULL)
 {
  cout<<"empty\n";
  return 0;
 }
 int cnt=0;
 Student *pt=head;
 while(pt)
 {
  ++cnt;
  cout<<pt->num<<" "<<pt->score<<endl;
  pt=pt->next;
 }
 return cnt;
}

void MyList::insert(int n, double s)
{
 Student * pt=new Student(n,s);
 pt->next =head;
 head=pt;
}

void MyList::append(int n,double s)
{
 Student * pt=new Student(n,s);
 if(head==NULL)
  head=pt;
 else
 {
  Student *pts=head;
  Student *pte=pts->next;
  while(pte)
  {
   pts=pte;
   pte=pts->next;
  }
  pts->next=pt;
 }
}

void MyList::cat(MyList& il)
{
 Student *pt=il.head;
 while(pt)
 {
  append(pt->num,pt->score);
  pt=pt->next;
 }
}

int MyList::length()
{
 int cnt=0;
 Student *pt=head;
 while(pt)
 {
  ++cnt;
  pt=pt->next ;
 }
 return cnt;
}

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; //输出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<<"head2: "<<endl;   //输出head2
 head2.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:
1 1
2 2
3 3
head1:
3 3
2 2
1 1
head2:
1001 98.4
1002 73.5
1003 92.8
1004 99.7
length of head2 after cat: 7
head2 after cat:
1001 98.4
1002 73.5
1003 92.8
1004 99.7
3 3
2 2
1 1
请按任意键继续. . .

 

原创粉丝点击