第十三周-链表类
2015-05-29 17:05
141 查看
#include <iostream> using namespace std; class Student //结点类 { public: Student(int n,double s):num(n), score(s), next(NULL) {} ~Student(); int num; double score; Student *next; //指向下一个结点 }; 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; //链表的头结点 }; Student::~Student() { if(!next) delete next; next=NULL; } 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; }
初始化列表的顺序应该是按照你成员声明顺序初始化
相关文章推荐
- 购买公网证书,导入到NetScaler中,LDAP认证失败
- iOS计算网络测试中的丢包率,延迟,下载速度等参数、iOS实现ping
- 52. C# -- 多线程
- 说全球语言,交世界大牛:技术大牛们快来呀!
- mysql位运算
- django+apache2+nginx+mod_wsgi
- Detected Maven Version: 3.0.2 is not in the allowed range 3.0.3
- JavaWeb将图片显示在浏览器中
- DOJO(二) 基本DOM操作
- SpringMVC入门学习(三)+Spring应用(整合)
- ATMEL精妙的IRQ中断处理过程
- C#(WinForm)实现软件注册
- 从今天开始DSP嵌入式控制系统的研发
- openstack 之 物理机时间设定
- 最新版SDWebImage的使用
- Liunx 下如何打开doc和docx
- 面试题5:打印链表的值
- oracle设置定时任务来调用存储过程完成统计(每小时计时一次存到hour表)
- java cxf webservice 生成客户端 调用 服务端
- 数据库之完全备份、差异备份以及增量备份