编号及代码:
/*
*Copyright(c)2015,烟台大学计算机与工程学院
*All rights reserved;
*文件名称:score.cpp
*作者:范星月
*完成日期:2015年6月1日
*版本号:v1.0
*
*问题描述:
*问题输入:动态链表
*问题输出:
*/
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,double s):num(n),score(s),next(NULL) {}
~Student()
{
if(!next)
delete next;
next=NULL;
};
Student *next;
int num;
double score;
};
class MyList
{
public:
MyList()
{
head=NULL;
}
MyList(int n,double s); //以Student(n,s)作为单结点的链表
~MyList();
int display();
void insert(int n,double s);
void append(int n,double s);
void cat(MyList &i1);
int length();
private:
Student *head;//链表的头结点
};
MyList::MyList(int n,double s)
{
head=new Student(n,s);
}
MyList::~MyList()
{
Student *p=head, *q;
while (p != NULL)
{
q = p;
p = p->next;
delete q;
}
head = NULL;
}
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;
for(int i=0; i<3; i++)
{
cin>>n>>s;
head1.insert(n,s);
}
cout<<"head1: "<<endl;
head1.display();
MyList head2(1001,98.4);
head2.append(1002,73.5);
head2.append(1003,92.8);
head2.append(1004,99.7);
cout<<"head2: "<<endl;
head2.display();
head2.cat(head1);
cout<<"length of head2 after cat:"<<head2.length()<<endl;
cout<<"head2 after cat:"<<endl;
head2.display();
return 0;
}
第12周项目4-1链表类
最新推荐文章于 2024-07-11 09:40:29 发布