/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2012, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:单链表
* 作 者: 刘镇
* 完成日期: 2012 年 05 月 21 日
* 版 本 号: 1.070
* 对任务及求解方法的描述部分
* 输入描述: ......
* 问题描述: ......
* 程序输出: ......
* 程序头部的注释结束
*/
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n,double s, string na, int a){num = n;score = s;name = na;age= a;next = NULL;}
Student *next;
int num;
double score;
string name;
int age;
};
class MyList
{
public:
MyList(){head = NULL;}
MyList(int n,double s, string na, int a){head = new Student(n, s, na, a);} //以Student(n,s)作为单结点的链表
int display(); //输出链表,返回值为链表中的结点数
void insert(int n,double s, string na, int a); //插入:将Student(n,s)结点插入链表,该结点作为第一个结点
void append(int n,double s, string na, int a); //追加:将Student(n,s)结点插入链表,该结点作为最后一个结点
void cat(MyList &il); //将链表il连接到当前对象的后面
int length(); //返回链表中的结点数
private:
Student *head;
};
int MyList::display()
{
Student *p = head;
int num = length();
cout << "num" << '\t' << "score" << '\t' << "name" << '\t' << "age" << endl;
for(int i = 1; i <= num; ++i)
{
cout << p->num << '\t' << p->score << '\t' << p->name << '\t' << p->age << endl;
p = p->next;
}
return length();
}
void MyList::insert(int n, double s, string na, int a)
{
if(head == NULL)
{
head = new Student(n, s, na, a);
}
else
{
Student *p = head;
head = new Student(n, s, na, a);
head->next = p;
}
}
int MyList::length()
{
int num = 0;
Student *p = head;
while(p != NULL)
{
num++;
p = p->next;
}
return num;
}
void MyList::cat(MyList &il)
{
Student *p = head, *q;
while(p != NULL)
{
q = p;
p = p->next;
}
q->next = il.head;
il.head = NULL;
}
void MyList::append(int n,double s, string na, int a)
{
if(head == NULL)
{
head = new Student(n, s, na, a);
head->next = NULL;
}
else
{
Student *p = head, *q;
while(p != NULL)
{
q = p;
p = p->next;
}
q->next = new Student(n, s, na, a);
p = q->next;
p->next = NULL;
}
}
int main()
{
int n;
double s;
string na;
int a;
MyList head1;
cout << "input head1: " << endl; //输入head1链表
for(int i = 0; i < 3; i++)
{
cin >> n >> s >> na >> a;
head1.insert(n, s, na, a); //通过“插入”的方式
}
cout << "head1: " << endl; //输出head1
head1.display();
MyList head2(1001, 98.4, "li", 22); //建立head2链表
head2.append(1002, 73.5, "liu", 21); //通过“追加”的方式增加结点
head2.append(1003, 92.8, "shi", 21);
head2.append(1004, 99.7, "jiang", 21);
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;
}
运行结果:
感言:
重在理解,把指针间的关系搞懂即可。