#include <iostream> using namespace std; template <class T> class Node { /********** Begin **********/ }; /********** End **********/ int main() { int a[10]; Node<int> n[10]; // cout << "输入10 个整数:" << endl; for (int i = 0; i < 10; i ++) { cin >> a[i]; } for (int i = 0; i < 9; i ++) { n[i].data = a[i]; n[i].insertAfter(&n[i+1]); } n[9].data = a[9]; Node<int>* np = &n[0]; while (np != NULL) { cout << np->data << ' '; np = np->nextNode(); } cout << endl; int f; // cout << "请输入要查找的数:"; cin >> f; Node<int> p(0, &n[0]); np = &p; while (np->nextNode() != NULL) { while (np->nextNode() != NULL && np->nextNode()->data == f) np->deleteAfter(); if(np->nextNode() != NULL) np = np->nextNode(); } // cout << "删除后的链表:" << endl; np = p.nextNode(); while (np != NULL) { cout << np->data << ' '; np = np->nextNode(); } np = &p; while (np->nextNode() != NULL) np->deleteAfter(); cout << endl; return 0; }补充代码完整
时间: 2024-02-27 19:51:25 浏览: 64
使用include <iostream>时一定要加using namespace std
完整代码如下:
```
#include <iostream>
using namespace std;
template <class T>
class Node {
public:
T data;
Node<T>* next;
Node(T d = 0, Node<T>* n = NULL): data(d), next(n) {}
void insertAfter(Node<T>* p) {
p->next = next;
next = p;
}
void deleteAfter() {
Node<T>* p = next;
next = p->next;
delete p;
}
Node<T>* nextNode() {
return next;
}
};
int main() {
int a[10];
Node<int> n[10];
cout << "输入10个整数:" << endl;
for (int i = 0; i < 10; i ++) {
cin >> a[i];
}
for (int i = 0; i < 9; i ++) {
n[i].data = a[i];
n[i].insertAfter(&n[i+1]);
}
n[9].data = a[9];
Node<int>* np = &n[0];
while (np != NULL) {
cout << np->data << ' ';
np = np->nextNode();
}
cout << endl;
int f;
cout << "请输入要查找的数:";
cin >> f;
Node<int> p(0, &n[0]);
np = &p;
while (np->nextNode() != NULL) {
while (np->nextNode() != NULL && np->nextNode()->data == f)
np->deleteAfter();
if(np->nextNode() != NULL)
np = np->nextNode();
}
cout << "删除后的链表:" << endl;
np = p.nextNode();
while (np != NULL) {
cout << np->data << ' ';
np = np->nextNode();
}
np = &p;
while (np->nextNode() != NULL)
np->deleteAfter();
cout << endl;
return 0;
}
```
在 Node 类中,实现了插入节点、删除节点和获取下一个节点的操作。在主函数中,完整输入了 10 个整数,并将它们依次插入到链表中。在输出链表元素后,输入要查找的数,从链表中删除所有值等于该数的节点,并输出删除后的链表。
阅读全文