再来个C++版本的#include <iostream>
using std::cout, std::endl;
using std::ostream;
class list_t {
struct node_t {
node_t *prev, *next;
int data, freq;
node_t(node_t *prev = nullptr, node_t *next = nullptr, int data = 0, int freq = 0):
prev(prev), next(next), data(data), freq(freq) {}
};
node_t *node = nullptr;
static void free_list(node_t *node) {
if(!node) return;
free_list(node->next);
delete node;
}
list_t(const list_t &list) = delete;
list_t &operator=(const list_t &list) = delete;
public:
list_t(const int data[], size_t size) {
node_t *h = NULL, **pn = &this->node;
for(size_t i = 0; i < size; ++i) {
*pn = new node_t(h, nullptr, data[i], 0);
h = *pn;
pn = &h->next;
}
}
~list_t() {free_list(this->node);}
bool locate_node(int x) {
for(node_t *i = this->node; i; i = i->next) {
if(i->data != x) continue;
++i->freq; return true;
}
return false;
}
friend ostream &operator<<(ostream &os, const list_t &list) {
for(const node_t *i = list.node; i; i = i->next) {
os << i->data << " ";
}
os << endl;
for(const node_t *i = list.node; i; i = i->next) {
os << i->freq << " ";
}
return os;
}
};
int main(void) {
int a[5] = {1, 2, 3, 4, 5};
list_t list(a, 5);
cout << list << endl;
cout << list.locate_node(4) << endl;
cout << list << endl;
return 0;
}
|