第十五周上机任务项目2-建立专门的链表类处理有关动态链表的操作

来源:互联网 发布:淘宝现货是什么意思 编辑:程序博客网 时间:2024/06/05 16:06
01./*     02.* 程序的版权和版本声明部分     03.* Copyright (c)2013, 烟台大学计算机学院学生     04.* All rightsreserved.     05.* 文件名称:  Student.cpp                                06.* 作    者:赵冠哲                                 07.* 完成日期:2013年6月7日     08.* 版本号: v1.0           09.* 输入描述:     10.* 问题描述:   11.*/        #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); //以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(){    Student *p=head;    int count=0;    while(p!=NULL)    {        cout<<p->num<<" "<<p->score<<endl;        p=p->next;       count++;    }    return count;}void MyList::insert(int n, double s){    Student *p=new Student(n, s);    p->next = head;    head = p;}void MyList::append(int n, double s){    Student *p = head, *q;    while(p!=NULL)    {        q=p;        p=p->next;    }    q->next=new Student(n, s);}void MyList::cat(MyList &il){    Student *p=head,*q;    while(p!=NULL)    {        q=p;        p=p->next;    }}int MyList::length(){   Student *p=head;    int count=0;    while(p!=NULL) {      p=p->next;        count++;    }   return count;}//测试函数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; //输出head1head1.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;   //输出head2head2.display();head2.cat(head1);   //把head1追加到head2后面cout<<"length of head2 after cat: "<<head2.length()<<endl;cout<<"head2 after cat: "<<endl;   //显示追加后的结果head2.display();return 0;}

原创粉丝点击