题目:
1. 请创建一个数据类型为T的链表类模板List,实现以下成员函数:
1) 默认构造函数List(),将该链表初始化为一个空链表(10分)
2) 拷贝构造函数List(constList<T>& list),根据一个给定的链表构造当前链表(10分)
3) 析构函数~List(),释放链表中的所有节点(10分)
4) Push_back(T e)函数,往链表最末尾插入一个元素为e的节点(10分)
5) operator<<()友元函数,将链表的所有元素按顺序输出(10分)
6) operator=()函数,实现两个链表的赋值操作(10分)
7) operator+()函数,实现两个链表的连接,A=B+C(10分)
2. 请编写main函数,测试该类模板的正确性:
1) 用List模板定义一个List<int>类型的模板类对象int_listB,从键盘读入m个整数,调用Push_back函数将这m个整数依次插入到该链表中;(4分)
2) 用List模板定义一个List<int>类型的模板类对象int_listC,从键盘读入n个整数,调用Push_back函数将这n个整数依次插入到该链表中;(4分)
3) 用List模板定义一个List<int>类型的模板类对象int_listA,调用List的成员函数实现A = B + C;(4分)
4) 用cout直接输出int_listA的所有元素(3分)
5) 用List模板定义List<double>类型的模板类对象double_listA,double_listB, double_listC,重复上述操作。(15分)
3. 输入输出样例:
1) 输入样例
4
12 23 34 45
3
56 67 78
3
1.2 2.3 3.4
4
4.5 5.6 6.7 7.8
2) 输出样例
12 23 34 45 56 67 78
1.2 2.3 3.4 4.5 5.6 6.7 7.8
代码(Node.h):
#ifndef __NODE__H_
#define __NODE__H_
template <class T>
struct Node
{
T data;
Node<T>* next;
};
#endif
代码(List.h):
#ifndef __LIST__H_
#define __LIST__H_
#include "Node.h"
#include <iostream.h>
template <class T>
class List
{
protected:
Node<T>* head;
Node<T>* tail;
public:
List();
List(const List<T>& list);
~List();
void Push_back(T e);
List<T> operator=(const List<T>& list);
List<T> operator+(const List<T>& list);
friend ostream& operator<<(ostream& out,const List<T>& list);
private:
void clear();
};
template <class T>
List<T>::List()
{
head=tail=NULL;
}
template <class T>
List<T>::List(const List<T>& list)
{
head=tail=NULL;
Node<T>* h=list.head;
while(h!=NULL)
{
Push_back(h->data);
h=h->next;
}
}
template <class T>
List<T>::~List()
{
clear();
}
template <class T>
void List<T>::Push_back(T e)
{
Node<T>* tmp=new Node<T>;
tmp->data=e;
tmp->next=NULL;
if(head==NULL)
{
head=tmp;
}
else
{
tail->next=tmp;
tail=tmp;
}
}
template <class T>
List<T> List<T>::operator=(const List<T>& list)
{
clear();
Node<T>* h=list.head;
while(h!=NULL)
{
Push_back(h->data);
h=h->next;
}
return *this;
}
template <class T>
List<T> List<T>::operator+(const List& list)
{
List<T> tmp;
Node<T>* h=head;
while(h!=NULL)
{
tmp.Push_back(h->data);
h=h->next;
}
return *this;
h=list.head;
while(h!=NULL)
{
tmp.Push_back(h->data);
h=h->next;
}
return tmp;
}
template <class T>
ostream& operator<<(ostream& out,const List<T>& list)
{
Node<T>* h=list.head;
while(h!=NULL)
{
out<<h->data<<" ";
h=h->next;
}
return out;
}
template <class T>
void List<T>::clear()
{
Node<T>* h=head;
while(h!=NULL)
{
Node<T>* pre=h;
h=h->next;
delete pre;
}
head=tail=NULL;
}
#endif
测试的主函数(main):
#include "List.h"
#include <iostream>
int main()
{
int m,n,i;
List<int> int_listB;
cin>>m;
for(i=0;i<m;i++)
{
int x;
cin>>x;
int_listB.Push_back(x);
}
List<int> int_listC;
cin>>n;
for(i=0;i<n;i++)
{
int x;
cin>>n;
int_listC.Push_back(x);
}
List<int> int_listA;
int_listA=int_listB+int_listC;
cout<<int_listA;
return 0;
}