【问题描述】采用模板技术定义一个能够存储任何对象的链表类,能够从键盘读入存储的数据类型、数据个数和数据列表,并按照输入顺序输出数据列表
时间: 2024-02-13 09:04:56 浏览: 13
以下是一个能够存储任何对象的链表类的模板类的实现,以及一个示例程序,可以从键盘读入存储的数据类型、数据个数和数据列表,并按照输入顺序输出数据列表。
```c++
#include<iostream>
#include<vector>
#include<string>
using namespace std;
template<class T>
class Node {
public:
T val;
Node<T>* next;
Node() {
next = NULL;
}
Node(T a) {
val = a;
next = NULL;
}
friend class List<T>;
};
template<class T>
class List {
public:
List() {
head = NULL;
}
void insert(T a) {
Node<T>* node = new Node<T>(a);
if (head == NULL) {
head = node;
return;
}
Node<T>* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
void print() {
Node<T>* p = head;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
private:
Node<T>* head;
};
int main() {
int kind, cnt;
cin >> kind >> cnt;
if (kind == 0) {
List<int> intList;
for (int i = 0; i < cnt; i++) {
int temp;
cin >> temp;
intList.insert(temp);
}
intList.print();
}
else if (kind == 1) {
List<float> floatList;
for (int i = 0; i < cnt; i++) {
float temp;
cin >> temp;
floatList.insert(temp);
}
floatList.print();
}
else if (kind == 2) {
List<string> stringList;
for (int i = 0; i < cnt; i++) {
string temp;
cin >> temp;
stringList.insert(temp);
}
stringList.print();
}
return 0;
}
```
该程序通过读取输入的kind和cnt来判断创建哪种类型的链表,然后使用一个循环读取cnt个数据,将其插入到对应的链表中。最后,程序使用链表类的print()函数输出链表中所有元素。由于链表类是模板类,因此可以存储任何对象,包括整型、浮点型和字符串等。