14周任务2---单链表应用
来源:互联网 发布:手机学打字软件 编辑:程序博客网 时间:2024/06/05 02:52
#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; //指向Student类的指针 while(pt) //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; }
感言:陈老师讲过了,还是是懂非懂啊,希望老贺快给您的弟子们指点迷经吧!
- 14周任务2---单链表应用
- 14周任务2
- 14周任务2
- 第14周任务2
- 第14周任务2
- c++第七周任务-静态成员应用
- 第七周上机任务 静态成员应用
- C#--第2周实验--任务六--编写一个控制台应用--输出所有的水仙花数
- 异步任务的应用
- quartz 调度任务应用
- Linux 定时任务应用
- 嵌入式应用之-任务
- 第14周-任务2-链表类
- 第14周实验报告 任务2
- 第14周项目1任务2
- 14周任务1
- 14周任务1
- 14周 任务三
- ZOJ_Function 3061
- 搭ssh框架遇到的问题
- windbg检测句柄泄露(可定位到具体代码)
- RFS的web自动化验收测试——第3讲 工作区EDIT-1
- Darwin Calendar Server安装与配置
- 14周任务2---单链表应用
- CPropertySheet属性页对话框中各个按钮的ID值
- Linu消息队列
- linux下配置ip地址四种方法(图文)
- 堆和栈的区别(转过无数次的文章)
- MP3
- POJ1008浅析------玛雅历
- 多线程聊天程序
- 进程与线程的区别