好友
阅读权限10
听众
最后登录1970-1-1
|
Fyfe
发表于 2022-7-26 10:40
66吾爱币
//给定了一个iterator,但全虚,要自己写一个implement 一个iterator, 用处就是去遍历A3List, A3list里有一个方法是start,还有finish,我自己写的,应该是用来返回head指针这里很迷,不知道怎么去写自己的iterator,还有A3list里的start和finish, 求指点一二。
#ifndef A3Q2_ITERATOR_H
#define A3Q2_ITERATOR_H
#include "Comparable.h"
class Iterator {
public:
virtual bool has_next() = 0;
virtual Comparable *next() = 0;
virtual Comparable *remove() = 0;
virtual ~Iterator() = 0;
};
inline Iterator::~Iterator() = default;
#endif //A3Q2_ITERATOR_H
class MyIterator :public Iterator{
private:
A3Node *curr;
A3Node *top;
public :
MyIterator(A3Node node) {
curr = &node;
top = curr;
}
A3Node *getTop() {
return top;
}
A3Node *getCurr() {
return curr;
}
bool has_next() override {
bool result = true;
if (curr->get_next() == nullptr) {
result = false;
}
return result;
}
Comparable *next() override {
return curr->get_next()->get_data();
}
Comparable *remove() override {//remove curr
curr = nullptr;
return nullptr;
}
};
class A3Node : public A3Object {
private:
Comparable *data;
A3Node *next;
public:
A3Node(Comparable *data, A3Node *next) {
this->data = data;
this->next = next;
}
A3Node *get_next() {
return next;
}
void set_next(A3Node *new_next) {
next = new_next;
}
Comparable *get_data() {
return data;
}
};
class A3List : public Collection {
private:
A3Node *head;
public:
A3List();
Iterator *start() override;
void finish(Iterator *i) override;
Comparable *remove(Comparable *item);
Comparable *find_by_key(std::string key);
~A3List();
protected:
void insert_natural(Comparable *item);
void insert_comparator(Comparable *item, Comparator *comp);
};
A3List::A3List() {
head = nullptr;
}
A3List::~A3List() {
A3Node *curr = head, *next;
while (nullptr != curr) {
next = curr->get_next();
delete curr;
curr = next;
}
}
void A3List::insert_natural(Comparable *item) {
class : public Comparator {
public:
int compare(Comparable *a, Comparable *b) {
return a->compareTo(b);
}
} natural_comparator;
insert_comparator(item, &natural_comparator);
}
void A3List::insert_comparator(Comparable *item, Comparator *comp) {
A3Node *curr = head, *prev = nullptr;
while (nullptr != curr && comp->compare(item, curr->get_data()) > 0) {
prev = curr;
curr = curr->get_next();
}
if (nullptr == prev) {
head = new A3Node(item, head);
} else {
prev->set_next(new A3Node(item, curr));
}
}
Comparable *A3List::remove(Comparable *item) {
A3Node *curr = head, *prev = nullptr;
while (nullptr != curr && item != curr->get_data()) {
prev = curr;
curr = curr->get_next();
}
if (nullptr == curr) {
return nullptr;
} else {
if (nullptr == prev) {
head = curr->get_next();
} else {
prev->set_next(curr->get_next());
}
Comparable *data = curr->get_data();
delete curr;
return data;
}
}
Iterator *A3List::start() {
MyIterator *top = new MyIterator(*head);
return top;
}
void A3List:: finish(Iterator *i) {
while (i->has_next()) {
remove(i->next());
}
} |
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|