您的位置:首页 > 其它

第14周任务2(建立专门的链表类处理有关动态链表的操作)

2012-05-22 21:59 417 查看
/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作    者:   臧鹏
* 完成日期:   2012   年 5月  22   日
* 版 本 号:

* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:建立专门的链表类处理有关动态链表的操作

* 程序输出:
* 程序头部的注释结束
*/

#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;
};
void MyList::insert(int n,double s)  //插入:将Student(n,s)结点插入链表,该结点作为第一个结点
{
Student *p1 = head;
head = new Student(n,s);
head->next = p1;
}
void MyList::append(int n,double s)  //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点
{
Student *p2 = head;
while(p2->next != NULL)
{
p2 = p2->next;
}
p2->next = new Student(n,s);

}
void MyList::cat(MyList &il) //将链表il连接到当前对象的后面
{
Student *p3=head;
while(p3->next != NULL)
{
p3 = p3->next;
}
p3->next=il.head;

}
int MyList::length()  //返回链表中的结点数
{
int length=0;
Student *p=head;
while(p->next != NULL)
{
p = p->next;
++length;
}
return length;
}
int MyList::display()  //输出链表,返回值为链表中的结点数
{
Student *p = head;
int length = 0;
while(p->next != NULL)
{
cout<<"num="<<p->num<<"score="<<p->score<<endl;
length++;
p = p->next;
}
return length;

}
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;
}




小小链表真不是个简单易懂的东西,要想玩儿的熟,还带多体会啊
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐