#include <iostream>
using namespace std;
template <class T>
class Node
{
public:
Node():next(NULL){}
Node *next;
T data;
};
template <class T>
class MyList
{
public:
int display()
{
Node<T> *a = head;
int i = 0;
for (;a->next != NULL; ++i)
{
cout << a->data << " ";
a = a->next;
}
cout << a->data << " ";
return i + 1;
}
void firstinsert(Node<T> &a)
{
Node<T>* node = new Node<Student> (a);
if (head == NULL)
{
head = node;
}
else
{
node->next = head;
head = node;
}
}
void append(Node<T> & b)
{
Node<T>* node = new Node<Student> (b);
Node<T> *a = head;
for (int i = 0; a->next != NULL; ++i)
{
a = a->next;
}
a->next = node;
}
MyList()
{
head=NULL;
}
MyList(Node<T> a)
{
head = new Node<T> (a);
}
void cat(MyList &il)
{
Node<T> *a = head;
for (int i = 0; a->next != NULL; ++i)
{
a = a->next;
}
a->next = il.head;
}
int length()
{
Node<T> *a = head;
int i = 0;
for (; a->next != NULL; ++i)
{
a = a->next;
}
return i + 1;
}
Node<T>* headarr ()
{
return this->head;
}
private:
Node<T> *head;
};
class Student
{
public:
Student(int n = 0, double s = 0):num(n), score(s){}
int num;
double score;
friend ostream& operator << (ostream & out, Student &A);
};
ostream& operator << (ostream & out, Student &A)
{
out << A.num << " " << A.score << " ";
return out;
}
int main()
{
int n;
double s;
MyList<Student> head1;
Node<Student> node;
cout<<"input head1: "<<endl; //输入head1链表
for(int i=0;i<3;i++)
{
cin>>n>>s;
node.data.num = n;
node.data.score = s;//通过“插入”的方式
head1.firstinsert(node);
}
cout<<"head1: "<<endl; //输出head1
head1.display();
cout << endl;
Node<Student> nod;
MyList<Student> head2(node); //建立head2链表
for(int i=0;i<3;i++)
{
cin>>n>>s;
node.data.num = n;
node.data.score = s;
head2.append(node);
}
cout<<"head2: "<<endl; //输出head2
head2.display();
cout << endl;
head2.cat(head1); //反head1追加到head2后面
cout<<"length of head2 after cat: "<< endl << head2.length() << endl;
cout<<"head2 after cat: "<<endl; //显示追加后的结果
head2.display();
system("pause");
return 0;
}
07-24
07-24