3、编写程序,对单链表做生成运算。 1)头插法 2)尾插法 3)改写为类模板,将上述两个封装为Link类中的方法。
时间: 2023-06-14 13:03:53 浏览: 64
以下是使用C++编写的单链表生成程序,包含头插法和尾插法,以及改写为类模板的Link类实现:
```c++
#include <iostream>
using namespace std;
// 定义单链表结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 头插法
ListNode* createListHead(int n) {
ListNode* head = new ListNode(-1); // 创建头节点
for (int i = 0; i < n; i++) {
int x;
cin >> x;
ListNode* node = new ListNode(x);
node->next = head->next;
head->next = node;
}
return head;
}
// 尾插法
ListNode* createListTail(int n) {
ListNode* head = new ListNode(-1); // 创建头节点
ListNode* tail = head; // 尾节点初始化为头节点
for (int i = 0; i < n; i++) {
int x;
cin >> x;
ListNode* node = new ListNode(x);
tail->next = node;
tail = node; // 更新尾节点
}
return head->next;
}
// Link类模板
template <typename T>
class Link {
public:
// 头插法
ListNode* createListHead(int n) {
ListNode* head = new ListNode(-1);
for (int i = 0; i < n; i++) {
T x;
cin >> x;
ListNode* node = new ListNode(x);
node->next = head->next;
head->next = node;
}
return head;
}
// 尾插法
ListNode* createListTail(int n) {
ListNode* head = new ListNode(-1);
ListNode* tail = head;
for (int i = 0; i < n; i++) {
T x;
cin >> x;
ListNode* node = new ListNode(x);
tail->next = node;
tail = node;
}
return head->next;
}
};
int main() {
int n;
cin >> n;
// 头插法
ListNode* head1 = createListHead(n);
ListNode* p1 = head1;
while (p1) {
cout << p1->val << " ";
p1 = p1->next;
}
cout << endl;
// 尾插法
ListNode* head2 = createListTail(n);
ListNode* p2 = head2;
while (p2) {
cout << p2->val << " ";
p2 = p2->next;
}
cout << endl;
// Link类模板
Link<int> link;
ListNode* head3 = link.createListHead(n);
ListNode* p3 = head3;
while (p3) {
cout << p3->val << " ";
p3 = p3->next;
}
cout << endl;
ListNode* head4 = link.createListTail(n);
ListNode* p4 = head4;
while (p4) {
cout << p4->val << " ";
p4 = p4->next;
}
cout << endl;
return 0;
}
```
注意,在使用类模板时,需要使用`Link<int>`这样的语法来具体化模板类类型。同时,头插法和尾插法的实现也需要使用模板类型。