第十三周阅读项目(6):链表类 .
来源:互联网 发布:红帽linux是什么 编辑:程序博客网 时间:2024/05/02 06:12
代码:
#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); //插入:将Student(n,s)结点插入链表,该结点作为第一个结点 void append(int n,double s); //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点 void cat(MyList &il); //将链表il连接到当前对象的后面 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; //输入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(); return 0;}
运行结果:
学习心得:
感觉写起来比较费劲,是看着答案才出的最后结果,很多地方自己都想不起来怎么写了,看来不复习真的忘得很快。
0 0
- 第十三周阅读项目(6):链表类 .
- 第十三周阅读项目(5):链表类
- 第十三周阅读项目(虚函数)
- 第十三周阅读项目(虚析构函数)
- 第十三周阅读项目-4-(2)
- 第十三周阅读项目二
- 第十三周阅读项目四
- 第十三周阅读项目六
- 第十三周项目-阅读项目-4-(3)
- 第十三周项目-阅读项目1
- 第十三周阅读项目 项目2
- 第十三周阅读项目(1):虚函数
- 第十三周阅读项目(2):虚析构函数
- 第十三周阅读项目(3):纯虚函数
- 第十三周阅读项目(4):多态性与虚函数
- 第十三周阅读项目(纯虚构函数)
- 第十三周项目-阅读程序-2
- 第十三周项目-阅读程序-3
- ubuntu 下 visudo的使用
- 利用awk命令提取字符串中的所有数字
- AS导入ApiDemos
- jquery方式的ajax方法失效,在火狐里边调试显示$.ajax为undefined
- Ubuntu15.04+Wine+QQ6.8成功安装运行
- 第十三周阅读项目(6):链表类 .
- 唐山哪个治自闭症
- c# 设置窗体初始化为居中显示
- 关于手机号正则表达式
- android4.0+ 以上如何用通用方法打开日历
- PAT 1017. Queueing at Bank
- 第12周-程序阅读-多态性与抽象类-纯虚函数
- android 获取网络图片
- oralce初始化