cpp中怎么实现一个list,元素是任意形式
时间: 2024-05-05 08:15:15 浏览: 11
在C++中,可以使用模板来实现一个通用的List,其中元素的类型可以是任意形式。
下面是一个简单的List实现代码:
```
template<typename T>
class List {
private:
struct Node {
T data;
Node* next;
Node(const T& d) : data(d), next(nullptr) {}
};
Node* head;
public:
List() : head(nullptr) {}
~List() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void push_front(const T& d) {
Node* temp = new Node(d);
temp->next = head;
head = temp;
}
void push_back(const T& d) {
Node* temp = new Node(d);
if (!head) {
head = temp;
}
else {
Node* p = head;
while (p->next) {
p = p->next;
}
p->next = temp;
}
}
void print() {
Node* p = head;
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
};
```
使用示例:
```
List<int> list1;
list1.push_front(1);
list1.push_front(2);
list1.push_back(3);
list1.push_back(4);
list1.print();
List<string> list2;
list2.push_front("hello");
list2.push_front("world");
list2.push_back("cpp");
list2.push_back("is fun");
list2.print();
```
输出:
```
2 1 3 4
world hello cpp is fun
```