2)编写程序link.h实现例9-6的链表类。在测试程序lab9_2.cpp中声明两个整型链表A和B,分别插入5个元素,然后把B中的元素加入A的尾部。
时间: 2024-03-05 10:50:15 浏览: 28
以下是link.h的代码实现:
```c++
#ifndef LINK_H
#define LINK_H
template<class T>
struct node {
T data;
node<T> *next;
node(const T& d, node<T>* n = nullptr) : data(d), next(n) {}
};
template<class T>
class link {
private:
node<T> *head;
public:
link() : head(nullptr) {}
void insert(T value) {
node<T> *newNode = new node<T>(value);
if (head == nullptr) {
head = newNode;
} else {
node<T> *current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
void print() {
node<T> *current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
void append(link<T>& other) {
if (head == nullptr) {
head = other.head;
} else {
node<T> *current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = other.head;
}
other.head = nullptr;
}
};
#endif
```
以下是lab9_2.cpp的测试程序:
```c++
#include <iostream>
#include "link.h"
using namespace std;
int main() {
link<int> A, B;
for (int i = 1; i <= 5; i++) {
A.insert(i);
B.insert(i * 10);
}
cout << "List A: ";
A.print();
cout << "List B: ";
B.print();
A.append(B);
cout << "List A after appending B: ";
A.print();
return 0;
}
```
该程序定义了一个链表类link,其中包括插入和打印链表的操作,以及将另一个链表追加到当前链表末尾的操作。在main函数中,我们创建了两个link<int>对象A和B,并向它们中插入若干个元素,然后调用A的append方法将B中的元素追加到A的末尾,并打印出A和B的内容。