)编写程序Node.h 实现例9-5的结点类,并编写测试程序lab91.cpp实现链表的基本操作。
时间: 2024-03-05 07:50:12 浏览: 44
以下是Node.h的代码实现:
```c++
#ifndef NODE_H
#define NODE_H
template<class T>
class Node {
public:
T data;
Node<T> *next;
Node() : next(nullptr) {}
Node(const T& d, Node<T>* n = nullptr) : data(d), next(n) {}
};
#endif
```
以下是lab91.cpp的测试程序:
```c++
#include <iostream>
#include "Node.h"
using namespace std;
template<class T>
class LinkedList {
private:
Node<T> *head;
public:
LinkedList() : head(nullptr) {}
void insert(T value) {
Node<T> *newNode = new Node<T>(value);
if (head == nullptr) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
bool remove(T value) {
if (head == nullptr) {
return false;
} else if (head->data == value) {
Node<T> *temp = head;
head = head->next;
delete temp;
return true;
} else {
Node<T> *current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node<T> *temp = current->next;
current->next = current->next->next;
delete temp;
return true;
} else {
return false;
}
}
}
void print() {
Node<T> *current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList<int> list;
list.insert(3);
list.insert(7);
list.insert(4);
list.insert(2);
list.print();
list.remove(7);
list.remove(1);
list.print();
return 0;
}
```
该程序定义了一个简单的链表类LinkedList,其中包括插入、删除和打印链表的操作。在main函数中,我们创建了一个LinkedList对象,向其中插入若干个元素,并进行删除和打印操作。